Publicar image en twitter usando twitterkit

Estoy intentando publicar una image y twittear usando Twitters nuevo TwitterKit con una interfaz de usuario personalizada. La única documentation que proporcionan es cómo hacerlo con sus puntos de vista.

así que puedo descubrir cómo hacerlo sin una image

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links", nil]; NSURLRequest* request = [twAPIClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:nil]; [twAPIClient sendTwitterRequest:request completion:^(NSURLResponse* response, NSData* data, NSError* connectionError){ }]; 

Pero su método URLRequestWithMethod no es mutable. ¿Cómo podría agregarle una image? Solías hacerlo con el SLRequest con

 [postRequest addMultipartData:UIImageJPEGRepresentation(image, 0.5) withName:@"media" type:@"image/jpeg" filename:@"image.png"]; 

Lo he descubierto.

Primero debes publicar la image en twitter.

 NSString *media = @"https://upload.twitter.com/1.1/media/upload.json"; NSData *imageData = UIImageJPEGRepresentation(image, 0.9); NSString *imageString = [corgiData base64EncodedStringWithOptions:0]; NSURLRequest *request = [client URLRequestWithMethod:@"POST" URL:media parameters:@{@"media":imageString} error:&requestError]; [[[Twitter shanetworkingInstance] APIClient] sendTwitterRequest:request completion:^(NSURLResponse *urlResponse, NSData *data, NSError *connectionError) { }]; 

luego, en el object de respuesta, usa la cadena media_id_ y agrega eso al parámetro del código en mi pregunta.

Asi que

 NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links",mediaIDString, @"media_ids", nil]; NSURLRequest* request = [twAPIClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:nil]; [twAPIClient sendTwitterRequest:request completion:^(NSURLResponse* response, NSData* data, NSError* connectionError){ NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&parsingError]; }]; 

tenga en count el object media_ids que es de la respuesta de la primera request

 NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links",[responseDict objectForKey:@"media_id_string"], @"media_ids", nil]; 

Entonces puede ponerlo dentro del bloque de finalización y publicará la image y el tweet.

Rápido

 func post (tweetString: String, tweetImage: NSData) { let uploadUrl = "https://upload.twitter.com/1.1/media/upload.json" let updateUrl = "https://api.twitter.com/1.1/statuses/update.json" let imageString = tweetImage.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) let request = Twitter.shanetworkingInstance().APIClient.URLRequestWithMethod("POST", URL: uploadUrl, parameters: ["media": imageString], error: nil) Twitter.shanetworkingInstance().APIClient.sendTwitterRequest(request, completion: { (urlResponse, data, connectionError) -> Void in if let mediaDict = self.nsdataToJSON(data!) { let validTweetString = TweetValidator().validTween(tweetString) let message = ["status": validTweetString, "media_ids": mediaDict["media_id_string"]] let request = Twitter.shanetworkingInstance().APIClient.URLRequestWithMethod("POST", URL: updateUrl, parameters: message, error:nil) Twitter.shanetworkingInstance().APIClient.sendTwitterRequest(request, completion: { (response, data, connectionError) -> Void in }) } }) } func nsdataToJSON (data: NSData) -> AnyObject? { do { return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) } catch let myJSONError { print(myJSONError) } return nil } 

A partir de abril de 2016, TwitterKit 2.0 de Fabric (o más reciente) expone un nuevo método uploadMedia para cubrir la parte de carga de medios. Aquí hay un código objc que funciona para mí.

 (earlier) self.userID = [[Twitter shanetworkingInstance] sessionStore].session.userID; - (void)tweetImage:(UIImage*)image { NSAssert([NSThread currentThread].isMainThread && self.userID, @"Twitterkit needs main thread, with self.userID set"); if (!self.userID) return; NSString *tweetStr = @"Look at me! I'm tweeting! #hashtag"; TWTRAPIClient *twitterClient = [[TWTRAPIClient alloc] initWithUserID:self.userID]; NSData *imgData = UIImageJPEGRepresentation(image, 0.6f); if (!imgData) { NSAssert(false, @"ERROR: could not make nsdata out of image"); return; } [twitterClient uploadMedia:imgData contentType:@"image/jpeg" completion:^(NSString * _Nullable mediaID, NSError * _Nullable error) { if (error) { NSAssert(false, @"ERROR: error uploading collage to twitter"); return; } NSError *urlerror = nil; NSURLRequest *request = [twitterClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:@{ @"status":tweetStr, @"media_ids":mediaID } error:&urlerror]; if (urlerror) { NSAssert(false, @"ERROR creating twitter URL request: %@", urlerror); return; } [twitterClient sendTwitterRequest:request completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { if (!connectionError && ((NSHTTPURLResponse*)response).statusCode != 200) { DDLogInfo(@"TwitterHelper tweetImage: non-200 response: %d. Data:\n%@", (int)((NSHTTPURLResponse*)response).statusCode, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } }]; }]; } 

Swift 3 más reciente

1) Compruebe que el inicio de session se realiza o no

 let store = Twitter.shanetworkingInstance().sessionStore if let store = store.session() { print("signed in as \(String(describing: store.authToken))"); print("signed in as \(String(describing: store.authTokenSecret))"); let postImage = UIImage(named: "testImage") let imageData = UIImagePNGRepresentation(postImage!) as Data? self.post(tweetString: "Test post image", tweetImage: (imageData! as NSData) as Data, withUserID: store.userID) } else { Twitter.shanetworkingInstance().logIn(completion: { (session, error) in if (session != nil) { print("login first time in twitter as \(String(describing: session?.userName))"); } else { print("error: \(String(describing: error?.localizedDescription))"); } }) } 

2) Para cargar la image con text

 func post(tweetString: String, tweetImage: Data ,withUserID :String) { let uploadUrl = "https://upload.twitter.com/1.1/media/upload.json" let updateUrl = "https://api.twitter.com/1.1/statuses/update.json" let imageString = tweetImage.base64EncodedString(options: NSData.Base64EncodingOptions()) let client = TWTRAPIClient.init(userID: withUserID) let requestUploadUrl = client.urlRequest(withMethod: "POST", url: uploadUrl, parameters: ["media": imageString], error: nil) client.sendTwitterRequest(requestUploadUrl) { (urlResponse, data, connectionError) -> Void in if connectionError == nil { if let mediaDict = self.nsDataToJSON(data: (data! as NSData) as Data) as? [String : Any] { let media_id = mediaDict["media_id_string"] as! String let message = ["status": tweetString, "media_ids": media_id] let requestUpdateUrl = client.urlRequest(withMethod: "POST", url: updateUrl, parameters: message, error: nil) client.sendTwitterRequest(requestUpdateUrl, completion: { (urlResponse, data, connectionError) -> Void in if connectionError == nil { if let _ = self.nsDataToJSON(data: (data! as NSData) as Data) as? [String : Any] { print("Upload suceess to Twitter") } } }) } } } } 

Nota: instale el pod de file pod 'TwitterKit'

importar TwitterKit