【问题标题】:Post image/video to twitter in swift快速将图像/视频发布到 Twitter
【发布时间】:2015-09-03 00:27:47
【问题描述】:

我正在使用 TwitterKit,我需要发布带有图片或视频以及描述的状态。麻烦的是它没有给我任何错误代码,所以我不知道为什么它不起作用。这是我到目前为止的代码:

编辑:好的,现在我打印出一个错误。错误是

Error uploading image Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x14604e90 {NSErrorFailingURLStringKey=https://upload.twitter.com/1.1/media/upload.json, NSErrorFailingURLKey=https://upload.twitter.com/1.1/media/upload.json, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x14611520 "The request timed out."})

编辑 2:好的,下面的所有代码都可以正常工作,除非我尝试上传视频,它会发回 400 错误错误请求

所以一切都是一样的,只是我从这里更改了媒体代码行:

var imageData : NSData = UIImageJPEGRepresentation(self.image!, 0.5)
                parameters["media"] = imageData.base64EncodedStringWithOptions(nil)

到这里

parameters["media"] = self.video!.base64EncodedStringWithOptions(nil) //self.video is NSData

这是代码:

 Twitter.sharedInstance().logInWithCompletion {
                    (session, error) -> Void in
                    if session != nil {
                        println("signed in as \(session.userName)")
                        let strUploadUrl = "https://upload.twitter.com/1.1/media/upload.json"
                        let strStatusUrl = "https://api.twitter.com/1.1/statuses/update.json"
                        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
                        var twAPIClient = Twitter.sharedInstance().APIClient
                        var error: NSError?
                        var parameters:Dictionary = Dictionary<String, String>()
                        // get image from bundle
                        var imageData : NSData = UIImagePNGRepresentation(self.image!)

                        parameters["media"] = imageData.base64EncodedStringWithOptions(nil)
    //for uploading video would I just do this parameters["media'] = NSData.dataWithContentsOfMappedFile(url.relativePath!) as? NSData
                        var twUploadRequest = twAPIClient.URLRequestWithMethod("POST", URL: strUploadUrl, parameters: parameters, error: &error)
                        if true {
                            twAPIClient.sendTwitterRequest(twUploadRequest) {
                                (uploadResponse, uploadResultData, uploadConnectionError) -> Void in
                                if (uploadConnectionError == nil) {
                                    // using SwiftyJSON to parse result
                                    let json = JSON(data: uploadResultData!)
                                    // check for media id in result
                                    if (json["media_id_string"].string != nil) {
                                        println("result = \(json)")
                                        // post a status with link to media
                                        parameters = Dictionary<String, String>()
                                        parameters["status"] = "Hey look at this"
                                        parameters["media_ids"] = json["media_id_string"].string!
                                        var twStatusRequest = twAPIClient.URLRequestWithMethod("POST", URL: strStatusUrl, parameters: parameters, error: &error)
                                        if true //(twStatusRequest != nil)
                                        {
                                            twAPIClient.sendTwitterRequest(twStatusRequest) { (statusResponse, statusData, statusConnectionError) -> Void in
                                                if (statusConnectionError != nil) {
                                                    println("Error posting status \(statusConnectionError)")
                                                }
                                            } // completion
                                        } else {
                                            println("Error creating status request \(error)")
                                        }
                                    } else {
                                        println("Media_id not found in result = \(json)")
                                    }
                                } else {
                                    println("Error uploading image \(uploadConnectionError)")
                                }
                            } // completion
                        } else {
                            println("Error creating upload request \(error)")
                        }
                        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                    }
                }

【问题讨论】:

  • 注意:println("Error creating upload request \(error)") 永远不会被执行,因为你问的是if true,这总是正确的。与println("Error creating status request \(error)") 相同。此外,您绝对应该阅读 statusResponse 中填充的内容,而不仅仅是检查错误,它可能会提供信息。
  • 好的,现在我收到一个错误消息...我想可能是图像格式错误或其他原因

标签: ios swift twitter


【解决方案1】:

最新的 Twitter API 使得在 Twitter 上发布带有图像和消息的推文变得非常容易。根据您上面的示例,下面是对我有用的示例代码。如果您遇到任何问题,请验证并告诉我。更多详情请访问 -> Twitter API's github page

TWTRTwitter.sharedInstance().logInWithCompletion {
                (session, error) -> Void in
                if session != nil {
                    println("signed in as \(session.userName)")

                    let twitterUserID = TWTRTwitter.sharedInstance().sessionStore.session()?.userIDUIApplication.sharedApplication().networkActivityIndicatorVisible = true
                    var twAPIClient = TWTRAPIClient(userID: twitterUserID)
                    twitterAPIclient.sendTweet(withText: "Hey look at this", image: self.image!, completion: {(tweet, error) in

        if tweet?.createdAt != nil {
            print("Tweet posted: \(tweet.debugDescription)")
        }
        if error?.localizedDescription != nil {
            print("error posting Tweet: \(error?.localizedDescription ?? "default error message")")
        }
    })     UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2017-02-08
    • 2015-07-06
    • 2015-04-24
    相关资源
    最近更新 更多