【问题标题】:Twitter API letting me post tweet via status but not upload media if I want to add imageTwitter API 让我通过状态发布推文,但如果我想添加图像,则不能上传媒体
【发布时间】:2016-10-15 18:28:48
【问题描述】:

登录并使用 Twitter 进行身份验证后,我能够成功地将推文(仅消息)发布到更新 url。

常量...

let kTwitterPOSTmethod = "POST"
let kTwitterUpdateURL = "https://api.twitter.com/1.1/statuses/update.json"
let kTwitterUploadURL = "https://upload.twitter.com/1.1/media/upload.json"

Twitter 客户端的东西......

  let store = Twitter.sharedInstance().sessionStore

  if let userid = store.session()?.userID {

    let client = TWTRAPIClient(userID: userid) //from logInWithCompletion() in the previous VC

....

}

当 base64Image 字符串为 ""... 时起作用的函数...

    if snapBase64String == "" {

    //just text (works!)

    var updateParams : [String : AnyObject] = ["status" : withMessage]

        if  let location = currentLocation {

            updateParams = ["status" : withMessage, "lat" : String(Float(location.latitude)), "long" : String(Float(location.longitude))]

    }


    //TODO: Handle error properly (do / catch?)

    let updateRequest = client.URLRequestWithMethod(kTwitterPOSTmethod, URL: kTwitterUpdateURL, parameters: updateParams as [NSObject : AnyObject], error: nil)
    //Lastly, we sent the status update along with the image that we parsed from the earlier request
    client.sendTwitterRequest(updateRequest, completion: { (response, data, connectionError) -> Void in

      if connectionError == nil {
        print("sendTwitterRequest(): \(response)")
        complete(success: true)
      }
      else {
        print("sendTwitterRequest(): \(connectionError)")
        complete(success: false)
      }
    })

    }

包含图像时不起作用的功能。我发布到上传网址并尝试使用 JSON 序列化程序函数获取 media_id_string,但它告诉我我未经授权。

    else {

        let postImageWithStatusRequest = client.URLRequestWithMethod(kTwitterPOSTmethod, URL: kTwitterUploadURL, parameters: ["media": snapBase64String], error: nil)

        client.sendTwitterRequest(postImageWithStatusRequest, completion: { (response, data, error) in

            if error != nil {

                print(error?.localizedDescription)
            }


            if let mediaDict = self.dataToJSON(data!) {

                let message = ["status": withMessage, "media_ids": mediaDict["media_id_string"]]

                let request = client.URLRequestWithMethod(kTwitterPOSTmethod,
                    URL: kTwitterUpdateURL, parameters: message as! [String : AnyObject], error:nil)

                client.sendTwitterRequest(request, completion: { (response, data, connectionError) -> Void in

                    if connectionError == nil {
                        print("sendTwitterRequest(): \(response)")
                        complete(success: true)
                    }
                    else {
                        print("sendTwitterRequest(): \(connectionError)")
                        complete(success: false)
                    }


                })
            }
        })

    }

JSON转换函数

class func dataToJSON(data: NSData) -> AnyObject? {

    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

我收到的错误消息...我需要不同的身份验证才能发布到服务器的上传部分吗?我不确定为什么它可以让我发布状态,但是当我想发布媒体时它不起作用。

▿ 可选 - 一些:错误域 = TwitterAPIErrorDomain 代码 = 32“请求失败:未经授权 (401)” UserInfo={NSErrorFailingURLKey=https://upload.twitter.com/1.1/media/upload.json, NSLocalizedDescription=请求失败:未经授权 (401), NSLocalizedFailureReason=Twitter API 错误:无法验证 你。 (代码 32)}

感谢您的帮助!

【问题讨论】:

  • 更新:我将参数“media”更改为“media_data”,我认为它应该是并且仍然得到相同的东西......

标签: ios swift twitter


【解决方案1】:

我想通了,它与身份验证无关,该错误非常具有误导性。

我所做的是改变了我对 base 64 字符串进行编码的方式。我只是将选项设置为空,而不是 64CharacterLineLength 一个,它起作用了!

let base64String = mapSnapData.base64EncodedStringWithOptions([])
snapBase64String = base64String

【讨论】:

    【解决方案2】:

    下面是我的工作代码。

    func shareToTwitter(){
    
    
        let store = Twitter.sharedInstance().sessionStore
        if let userid = store.session()?.userID {
            let client = TWTRAPIClient(userID: userid)
            let statusesShowEndpoint = "https://upload.twitter.com/1.1/media/upload.json"
    
            let image = UIImage(named: "How_To_Say_TY")
            let data = UIImagePNGRepresentation(image!)
            let strImage = data?.base64EncodedStringWithOptions([])
    
            let params  : [String : AnyObject] = ["media": strImage!]
            var clientError : NSError?
    
            let request = client.URLRequestWithMethod("POST", URL: statusesShowEndpoint, parameters: params, error: &clientError)
    
            client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
    
                if (connectionError == nil) {
    
                    do {
                        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                        print("test tweet :- \(json["media_id_string"])")
    
                        self.updateTwitterStatusWithMediaID("\(json["media_id_string"])")
    
                    } catch {
                        print("error serializing JSON: \(error)")
                    }
                }
                else {
                    print("Error: \(connectionError)")
                }
            }
        }
    }
    
    func updateTwitterStatusWithMediaID( mediaID : String ){
    
        let store = Twitter.sharedInstance().sessionStore
        if let userid = store.session()?.userID {
            let client = TWTRAPIClient(userID: userid)
            let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/update.json"
            let params = ["status": "Test by Carl.","media_ids":mediaID]
            var clientError : NSError?
    
            let request = client.URLRequestWithMethod("POST", URL: statusesShowEndpoint, parameters: params, error: &clientError)
    
            client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
    
                if (connectionError == nil) {
    
                    do {
                        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                        print("test tweet :- \(json)")
                    } catch {
                        print("error serializing JSON: \(error)")
                    }
                }
                else {
                    print("Error: \(connectionError)")
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-29
      • 2021-11-27
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      相关资源
      最近更新 更多