I want to post a photo to twitter from my iOS app. I can post a tweet without media but when i am trying to attach media it throws an error.
I am following twitter docu
Swift 4 latest
install pod file pod 'TwitterKit'
import TwitterKit
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-init.html
func PostTweetToTwitter() {
let twitter_USERID = UserDefaults.standard.string(forKey: Constants.Twitter.TWITTER_USER_ID)
let url = URL(string: "http://www.tinyeyeimage.com/picture/Photos/149802345.png")
let tweetImage = try? Data(contentsOf: url!)
let tweetString = "Welcome to the Twitter world!!"
let uploadUrl = "https://upload.twitter.com/1.1/media/upload.json"
let updateUrl = "https://api.twitter.com/1.1/statuses/update.json"
let imageString = tweetImage?.base64EncodedString(options: NSData.Base64EncodingOptions())
let client = TWTRAPIClient.init(userID: twitter_USERID)
let requestUploadUrl = client.urlRequest(withMethod: "POST", urlString: uploadUrl, parameters: ["media": imageString], error: nil)
client.sendTwitterRequest(requestUploadUrl) { (urlResponse, data, connectionError) -> Void in
if connectionError == nil {
if let mediaDict = self.dataToJSON(data: (data! as NSData) as Data) as? [String : Any] {
let media_id = mediaDict["media_id_string"] as! String
let message = ["status": tweetString, "media_ids": media_id]
let requestUpdateUrl = client.urlRequest(withMethod: "POST", urlString: updateUrl, parameters: message, error: nil)
client.sendTwitterRequest(requestUpdateUrl, completion: { (urlResponse, data, connectionError) -> Void in
if connectionError == nil {
if let _ = self.dataToJSON(data: (data! as NSData) as Data) as? [String : Any] {
print("Upload suceess to Twitter")
}
}
})
}
}
}
}