如何在 Swift 的单条推文中将多张图片上传到推特?

How to upload multiple images to twitter in single tweet in Swift?

我正在尝试将多张图片上传(分享)到 Twitter,但无法将所有图片上传到单条推文中。找不到与此相关的适当文档。可不可以?

我正在使用这个 link 上传媒体: Compose Tweets

我已经使用 TwitterKit.Call 这个函数 requestImageToTwitterAccount 从 Imagepickerview 选择图像后点击按钮共享多个图像来实现这个。

  func requestImageToTwitterAccount(image:UIImage,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.uploadImageToTwitter(imageURL: image, 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 uploadImageToTwitter(imageURL:UIImage,fileSize: UInt32){


    if let imageData : NSData = UIImageJPEGRepresentation(imageURL, 0.5)! as NSData{
            self.tweetImageInit(imageData: imageData, imageSize: Int(fileSize))

        }else{
            print("Something Wrong")
        }

}



func tweetImageInit(imageData:NSData,imageSize: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(imageData.length)
    params["media_type"]  = "image/jpeg"
    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
        print(urlREsponse)
        if let err = error {
            print(error)
        }else{
            do {
                let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
                print(responseData)
                if let dictionary = object as? [String: AnyObject] {
                    print(dictionary)
                    if let tweetID = dictionary["media_id_string"] as? String{
                        self.tweetImageApped(imageData: imageData, imageSize: imageSize, mediaId: tweetID, chunk: 0)
                    }
                }
            }
            catch {
                print(error)
            }
        }
    })
}



func tweetImageApped(imageData:NSData,imageSize: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(imageData as Data!, withName: "media", type: "image/jpeg", filename:"filename")

    postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
        print(urlREsponse)
        if let err = error {
            print(err)

        }else{
            self.tweetImageFinalize(mediaId: mediaId)
        }
    })
}



func tweetImageFinalize(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
        print(urlREsponse)
        if let err = error {
            print(err)
        }else{
            do {
                self.arrMediaID.append(mediaId)
                print(self.arrMediaID)
                let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
                if let dictionary = object as? [String: AnyObject] {
                    print(dictionary)

                    if self.arrMediaID.count == self.arrImage.count
                    {
                        self.postStatus(mediaId: self.arrMediaID)
                    }

                }
            }
            catch {
                print(error)
            }
        }
    })
}



func postStatus(mediaId:[String]) {

        let uploadURL = NSURL(string:"https://api.twitter.com/1.1/statuses/update.json")
        let array = mediaId
        let stringRepresentation = array.joined(separator: ",") 
        print(stringRepresentation)
        var params = [String:Any]()
        params["command"] = "STATUS"
        params["media_ids"]  = stringRepresentation
        print(params)
        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
           print(urlREsponse)
            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(dictionary)
                        print("video uploaded")
                        //self.videoURL = nil
                        self.arrImage.removeAll()
                        self.arrMediaID.removeAll()
                        let alert = UIAlertController(title: "Success", message: "video uploaded successfully.", preferredStyle: UIAlertControllerStyle.alert)
                        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                        self.present(alert, animated: true, completion: nil)
                    }
                }
                catch {
                    print(error)
                }
            }
        })
    }