【发布时间】: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”,我认为它应该是并且仍然得到相同的东西......