iOS - Unable to Upload media with Twitter/Fabric New SDK

twitter kit-ios tutorial
twitter integration in ios swift github
twitter api
twitter url scheme ios
twitter app card
twitter sdk ios swift
url or card twitter

I want to post a photo to twitter from my iOS app. I can post a tweet without media but when i am trying to attach media it throws an error.

I am following twitter documentation and according to that first I need to upload media to https://upload.twitter.com/1.1/media/upload.json and then I will be able to attach it with the tweet using media-id.

here is my code for uploading media.

App is crashing at URLRequestWithMedthod call.

Help me to resolve issue.

UIImage *image = [UIImage imageNamed:@"shareit.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
NSString *statusesShowEndpoint = @"https://upload.twitter.com/1.1/media/upload.json";
NSDictionary *params = @{@"media" : imageData};
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient] 
                         URLRequestWithMethod:@"POST"
                         URL:statusesShowEndpoint
                         parameters:params
                         error:&clientError];

if (request) {
    [[[Twitter sharedInstance] APIClient]
     sendTwitterRequest:request
     completion:^(NSURLResponse *response,
                  NSData *data,
                  NSError *connectionError) {
         if (data) {
             // handle the response data e.g.
             NSError *jsonError;
             NSDictionary *json = [NSJSONSerialization
                                   JSONObjectWithData:data
                                   options:0
                                   error:&jsonError];
             NSLog(@"%@",json);
         }
         else {
             NSLog(@"Error: %@", connectionError);
         }
     }];
}
else {
    NSLog(@"Error: %@", clientError);
}

Well it was pretty simple. All was missing is conversion of imagedata into base64EncodedString. Here is the solution.

   NSString *media = @"https://upload.twitter.com/1.1/media/upload.json";

   NSData *imageData = UIImageJPEGRepresentation(image, 0.9);

   NSString *imageString = [imageData base64EncodedStringWithOptions:0];
   NSError *error;
   NSURLRequest *request = [[[Twitter sharedInstance] APIClient] URLRequestWithMethod:@"POST" URL:media parameters:@{@"media":imageString} error:&error];

   [[[Twitter sharedInstance] APIClient] sendTwitterRequest:request completion:^(NSURLResponse *urlResponse, NSData *data, NSError *connectionError) {

       NSError *jsonError;
       NSDictionary *json = [NSJSONSerialization
                              JSONObjectWithData:data
                              options:0
                              error:&jsonError];
       NSLog(@"Media ID :  %@",[json objectForKey:@"media_id_string"]);

      // Post tweet With media_id
    }];

mtrung/TwitterVideoUpload: Share/upload video to Twitter , Share/upload video to Twitter for iOS. Contribute to Branch: master. New pull request to keep things light. No need to add extra frameworks such as TwitterKit and Fabric. Use new Twitter Uploading Media REST API, which was released in May 2015 If failed, errStr will contain REST response string. To add tweet text  In a blog post, the Fabric team noted its Crashlytics kit was also named the No. 1 most implemented SDK in a report from SourceDNA, which also deemed it the No. 1 most implemented mobile analytics SDK on iOS. "With Fabric, we symbolicate over 1,000 crashes per second to help customers identify, prioritize and resolve stability issues that have the biggest impact on their app quality," the post said.

Completing the Saani's answer

// Post tweet With media_id

mediaID = [json objectForKey:@"media_id_string"];
client = [[Twitter sharedInstance] APIClient];
message = @{@"status": title, @"wrap_links": @"true", @"media_ids": mediaID};

NSURLRequest *request = [client URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:&error];

[client sendTwitterRequest:request completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

    if (connectionError) {
        NSLog(@"error %@",[connectionError localizedDescription]);
    } else {
        NSError *jsonError;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
        NSLog(@"json Finish! %@",json);
    }
}];

Changelog · twitter-archive/twitter-kit-ios Wiki · GitHub, Twitter Kit is a native SDK to include Twitter content inside mobile apps. Added video upload with NSData. Fix issue where Bitcode was missing from a subset of files Added support for OAuth via the Twitter for iOS mobile app in -[Twitter Added new TWTRTweetDetailViewController to show a full-screen Tweet  It contains instructions for setting up with the Fabric Crashlytics SDK, which is a legacy SDK. You can also set up with the new Firebase Crashlytics SDK in beta, the official SDK for Firebase Crashlytics. Visit the Get started guide for the new SDK to find out how. iOS Android Unity. Before you begin

Sharing the swift 2.2 (Xcoe 7.3.2) code if anyone is still looking for help.

 let client = TWTRAPIClient.init(userID:<Twitter_User_Id_Here>)
let imgData =  UIImageJPEGRepresentation(UIImage(named:"Home")!, 0.7)
    client.uploadMedia(imgData!, contentType: "image/jpeg", completion: {(media_ids,error) in

        if error == nil{
            //prints the media_ids in String. 
      //Pass them into the params of status update params ["media_ids":<MEDIA_ID>]
            print(media_ids)
        }
        else{
            print(error?.localizedDescription)
        }
    })

To Send with status update.

   let request = client.URLRequestWithMethod("POST", URL: "https://api.twitter.com/1.1/statuses/update.json", parameters: ["status":"Hello World","media_ids":<Media_Ids_Here>], error: nil)

    client.sendTwitterRequest(request, completion: {
        (response,data,error)in
        if error == nil {
            print(data)

        }
        else{
            print("Error")
        }
    })
}

App card, This Card type is currently available on the twitter.com website, as well as iOS and Android mobile clients. It is not available on mobile web. Our system  Fabric is a mobile platform with modular kits you can mix and match to build the best apps. Fabric is tightly integrated into your dev environment, making adding new services a breeze. Start with what you need from Fabric today, and quickly add more kits as your needs grow.

Swift 4 latest

install pod file pod 'TwitterKit'

import TwitterKit

https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-init.html

func PostTweetToTwitter() {
        let twitter_USERID = UserDefaults.standard.string(forKey: Constants.Twitter.TWITTER_USER_ID)

        let url = URL(string: "http://www.tinyeyeimage.com/picture/Photos/149802345.png")
        let tweetImage = try? Data(contentsOf: url!)

        let tweetString = "Welcome to the Twitter world!!"

        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: twitter_USERID)

        let requestUploadUrl = client.urlRequest(withMethod: "POST", urlString: uploadUrl, parameters: ["media": imageString], error: nil)

        client.sendTwitterRequest(requestUploadUrl) { (urlResponse, data, connectionError) -> Void in
            if connectionError == nil {
                if let mediaDict = self.dataToJSON(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", urlString: updateUrl, parameters: message, error: nil)

                    client.sendTwitterRequest(requestUpdateUrl, completion: { (urlResponse, data, connectionError) -> Void in
                        if connectionError == nil {
                            if let _ = self.dataToJSON(data: (data! as NSData) as Data) as? [String : Any] {
                                print("Upload suceess to Twitter")
                            }
                        }

                    })
                }
            }
        }
    }

Introducing Twitter Kit 3, Twitter Kit 3 includes a rewritten composer to create Tweets inside experiences provided by the Twitter for iOS and Twitter for Android apps. For developers who installed Twitter Kit using CocoaPods, you're automatically able to access the new Maintaining your Twitter Kit app & Twitter API access Fabric is a mobile platform with modular kits you can mix and match to build the best apps. Fabric is tightly integrated into your dev environment, making adding new services a breeze. Start with what you need from Fabric today, and quickly add more kits as your needs grow.

Upload Files on Android, iOS · Android · Web Cloud Storage allows developers to quickly and easily upload files to a Google To upload a file to Cloud Storage, you first create a reference to the full path of the addOnSuccessListener(new OnSuccessListener<UploadTask. Register observers to listen for when the download is done or if it fails We have integrated the best of Fabric into Firebase to bring you one powerful app development platform. Fabric is deprecated and will be available until March 31, 2020. New users should start in Firebase to get Crashlytics, Google Analytics, and App Distribution. Learn more in our roadmap .

Use the iOS SDK, How to Use iOS SDK for Azure Mobile Apps. If you are new to Azure Mobile Apps, first complete Azure Mobile Apps Quick Start to create If the device is not able to present a WebView UI, then another method of authentication You can use Fabric for iOS to sign users into your application using Twitter. If you have set up the Fabric “run” script as a Build Phase in Xcode, no changes are needed. The run script has been modified to call upload-symbols with the correct parameters. If you call upload-symbols directly, the behavior of the existing command line arguments has not changed, so no action is needed.

You cannot upload data with a reference to the root of your Google Cloud Storage bucket. Your reference must point to a child URL. Upload Files. Once you have a reference, you can upload files to Cloud Storage in two ways: Upload from data in memory; Upload from a URL representing a file on device; Upload from data in memory

Comments
  • Did this actually work for you? I'm trying this and getting 503 Service Unavailable. How did you get this to work without oauth_* params?
  • @sun it will not work without oauth_* params. You need to login before using this.
  • Worked for me , Thanks !
  • how works that with multiple images? can you help me with this stackoverflow.com/questions/36559534/…