Thanks for getting me in the right direction. I thought that I would need an NSMutableURLRequest so that I could add the image data. I took the NSURLRequest from URLRequestWithMethod and cast it into a new NSMutableURLRequest, added the image data and sent it off, and then got a different error:
{code:“38”, message: “Media parameter is missing”}
So instead of adding the image data after getting the request from the framework I just decided to send it to the framework in the parameters to be included in the request. That worked. Here’s a complete sample:
func uploadThis(sender: UIButton)
{
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(UIImage(named: "SampleImage.png"))
// get anim gif from bundle
let path = NSBundle.mainBundle().pathForResource("SampleAnim", ofType: "GIF")
var animData : NSData = NSData(contentsOfFile: path!)!
// use either of these, media in parameters is put into request
// parameters["media"] = imageData.base64EncodedStringWithOptions(nil)
parameters["media"] = animData.base64EncodedStringWithOptions(nil)
var twUploadRequest = twAPIClient.URLRequestWithMethod("POST", URL: strUploadUrl, parameters: parameters, error: &error)
if twUploadRequest != nil {
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 (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
}
Naturally you’ll want to do something better than println the errors and you might want to break out the image and the status into separate operations but this works.
Mike