登录并通过Twitter进行身份验证后,我能够成功地将推文发送到更新网址。
常数......
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)}
感谢您的帮助!
答案 0 :(得分:0)
我弄清楚了,它与身份验证无关,错误非常具有误导性。
我所做的是改变我编码base 64字符串的方式。我只是将选项设置为空而不是64CharacterLineLength而且它有效!
let base64String = mapSnapData.base64EncodedStringWithOptions([])
snapBase64String = base64String
答案 1 :(得分:0)
以下是我的工作代码。
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)")
}
}
}
}