Upload Video To Twitter Using SLRequest


Here is the complete upload guide referred from twitter developer documentation!

Using the chunked POST media/upload endpoints requires an adjusted workflow from single image uploads. For video or chunked uploads, you must
  • Initialize the upload using the INIT command
  • Upload each chunk of bytes using the APPEND command
  • Complete the upload using the FINALIZE command
Please refer below link to look into video specifications and recommendations https://dev.twitter.com/rest/media/uploading-media.html

Example Code: Find the complete steps for uploading video to twitter.

STEP 1: Request for twitter account

func requestAccessToTwitterAccount(videoURL:NSURL,fileSize:UInt32){
         
  let accountStore = ACAccountStore()
  let twitterAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
         accountStore.requestAccessToAccounts(with: twitterAccountType, options: nil) { (granted, error) in
            
            if granted {
               let accounts = accountStore.accounts(with: twitterAccountType)
                if (accounts?.count)! > 0 {
                    self.twitterAccount = accounts?.last as! ACAccount
                    self.uploadVideoToTwitter(videoURL: videoURL, fileSize: fileSize)
                }else{
                        let error = "Please set your twitter account in Settings."
                        print(error)
                    }
                }
            } else {
                    print("App permissions are disabled in device twitter settings, please enable it.")
                }
            }
        }
    }

   func uploadVideoToTwitter(videoURL:NSURL,fileSize: UInt32{
        
        if let videoData = NSData(contentsOfFile: videoURL.path!){
            self.tweetVideoInit(videoData: videoData, videoSize: Int(fileSize))
        }
    }

STEP 2: POST media/upload (INIT)

The INIT command request is used to initiate a file upload session. It returns a media_id which should be used to execute all subsequent requests.
  

  func tweetVideoInit(videoData:NSData,videoSize:Int) {
        
        let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
        
        var params = [String:String]()
        
        params["command"] = "INIT"
        params["total_bytes"]  = String(videoData.length)
        params["media_type"]  = "video/mov"
        
        let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
                                    requestMethod: SLRequestMethod.POST,
                                    url: uploadURL as URL!,
                                    parameters: params)
        
        postRequest?.account = self.twitterAccount;
        
        postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
            if let err = error {
                print(error)
            }else{
                do {
                    let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
                    if let dictionary = object as? [String: AnyObject] {
                        
                        if let tweetID = dictionary["media_id_string"] as? String{
                            self.tweetVideoApped(videoData: videoData, videoSize: videoSize, mediaId: tweetID, chunk: 0)
                        }
                    }
                }
                catch {
                    print(error)
                }
            }
        })
    }




STEP 3: POST media/upload (APPEND)

The APPEND command is used to upload a chunk (consecutive byte range) of the media file. For example, a 3 MB file could be split into 3 chunks of size 1 MB, and uploaded using 3 APPEND command requests.

func tweetVideoApped(videoData:NSData,videoSize:Int ,mediaId:String,chunk:NSInteger) {
        
        let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
        
        var params = [String:String]()
        
        params["command"] = "APPEND"
        params["media_id"]  = mediaId
        params["segment_index"]  = String(chunk)
        
        let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
                                    requestMethod: SLRequestMethod.POST,
                                    url: uploadURL as URL!,
                                    parameters: params)
        
        postRequest?.account = self.twitterAccount;
        postRequest?.addMultipartData(videoData as Data!, withName: "media", type: "video/mov", filename:"mediaFile")
        
        postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
            if let err = error {
                print(err)
                
            }else{
                self.tweetVideoFinalize(mediaId: mediaId)
            }
        })
    }




 STEP 4: POST media/upload (FINALIZE)

The FINALIZE command should be called after the entire media file is uploaded using APPEND commands.

    func tweetVideoFinalize(mediaId:String) {
        let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
        
        var params = [String:String]()
        params["command"] = "FINALIZE"
        params["media_id"]  = mediaId
        
        let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
                                    requestMethod: SLRequestMethod.POST,
                                    url: uploadURL as URL!,
                                    parameters: params)
        
        postRequest?.account = self.twitterAccount;
        postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
            if let err = error {
                    print(err)
            }else{
                do {
                    let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
                    if let dictionary = object as? [String: AnyObject] {
                        self.postStatus(mediaId: mediaId)
                    }
                }
                catch {
                    print(error)
                }
            }
        })
    }
STEP 5: POST media/upload

func postStatus(mediaId:String) {
        
        let uploadURL = NSURL(string:"https://api.twitter.com/1.1/statuses/update.json")
        
        var params = [String:String]()
        params["status"] = twitterDescription
        params["media_ids"]  = mediaId
        
        let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
                                    requestMethod: SLRequestMethod.POST,
                                    url: uploadURL as URL!,
                                    parameters: params)
        
        postRequest?.account = self.twitterAccount;
        
        postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
            if let err = error {
               print(err)
            }else{
                do {
                    let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
                    if let dictionary = object as? [String: AnyObject] {                        
                        print("video uploaded")
                    }
                }
                catch {
                    print(error)
                }
            }
        })
    }
}




  
I hope this is helpful !! I can give link to my sample code if  required.
Please feel free to drop your suggestions in comments section.  

Comments

Popular Posts