2
func twitterSender(photoImported: UIImage) ->Void {
    let account = ACAccountStore()
    let accountType = account.accountTypeWithAccountTypeIdentifier(
        ACAccountTypeIdentifierTwitter)

    account.requestAccessToAccountsWithType(accountType, options: nil,
        completion: {(success: Bool, error: NSError!) -> Void in

            if success {
                let arrayOfAccounts =
                account.accountsWithAccountType(accountType)

                if arrayOfAccounts.count > 0 {
                    let twitterAccount = arrayOfAccounts.last as! ACAccount
                    var message = Dictionary<String, AnyObject>()
                    message["status"] = "My app test 5"
                    let imageData = UIImageJPEGRepresentation(photoImported, 0.9)
                    let imageString = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
                    message["media_ids"] = imageString
                    let requestURL = NSURL(string:
                        "https://api.twitter.com/1.1/statuses/update.json")
                    let postRequest = SLRequest(forServiceType:
                        SLServiceTypeTwitter,
                        requestMethod: SLRequestMethod.POST,
                        URL: requestURL,
                        parameters: message)

                    postRequest.addMultipartData(imageData, withName: "oauth_*", type: "application/octet-stream", filename: "image.jpg")
                    postRequest.account = twitterAccount

                    postRequest.performRequestWithHandler({
                        (responseData: NSData!,
                        urlResponse: NSHTTPURLResponse!,
                        error: NSError!) -> Void in

                        if let err = error {
                            println("Error : \(err.localizedDescription)")
                        }
                        println("Twitter HTTP response \(urlResponse.statusCode)")
                    })
                }
            }
    })

}

The problem of my code is that only text can be posted without image. I search a lot and try to find some information on twitter's website. But I am still really confused how to do it. Twitter used to have a API called POST statuses/update_with_media to do the job I want to do now. Unfortunately twitter discarded that API and uses a new one. So I indeed found some similar questions with mine, but all of them either uses objective-c or uses that old twitter API. Nothing is helpful for me. With a lot of research consuming me a lot of time it looks like I need to use addMultipartData to do the job, but I don't know how to fill these parameters or maybe this is a wrong direction either.

Colin
  • 21
  • 3

2 Answers2

1
func twitter(){
    let account = ACAccountStore()
    let accountType = account.accountTypeWithAccountTypeIdentifier(
        ACAccountTypeIdentifierTwitter)
    account.requestAccessToAccountsWithType(accountType, options: nil,completion: {(success: Bool, error: NSError!) -> Void in

        if success {
        let arrayOfAccounts = account.accountsWithAccountType(accountType)

        if arrayOfAccounts.count > 0 {
        let twitterAccount = arrayOfAccounts.last as! ACAccount
        var message = Dictionary<String, AnyObject>()
        message["status"] = self.txtPostDesc.text! //textbox
        let imageData = UIImagePNGRepresentation(self.imagePost)//pickerview add
        let imageString = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
        message["media_ids"] = imageString
        let requestURL = NSURL(string: "https://upload.twitter.com/1/statuses/update_with_media.json")
        let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.POST, URL: requestURL, parameters: message)

        postRequest.addMultipartData(imageData, withName: "media", type: nil, filename: nil)
            postRequest.account = twitterAccount

            postRequest.performRequestWithHandler({(responseData: NSData!,urlResponse: NSHTTPURLResponse!,error: NSError!) -> Void in

            if let err = error {
                print("Error : \(err.localizedDescription)")
            }
                print("Twitter HTTP response \(urlResponse.statusCode)")
                self.alertShow("successful")
                })

            }
        }
    })

}
  • 1
    I suggest you to improve your example by reading the [Minimal, Complete and verifiable example](http://stackoverflow.com/help/mcve). – IlGala Apr 27 '16 at 09:32
-1

You need to use update.json and provide the image with addMultipartData with NSData. Here is what works for me:

func tweetWithImage(data:NSData)
{

    let account = ACAccountStore()
    let accountType = account.accountTypeWithAccountTypeIdentifier(
        ACAccountTypeIdentifierTwitter)

    account.requestAccessToAccountsWithType(accountType, options: nil,
        completion: {(success: Bool, error: NSError!) -> Void in
            if success {
                let arrayOfAccounts =
                account.accountsWithAccountType(accountType)

                if arrayOfAccounts.count > 0 {
                    let twitterAccount = arrayOfAccounts.first as! ACAccount
                    var message = Dictionary<String, AnyObject>()
                    message["status"] = "Test Tweet with image"

                    let requestURL = NSURL(string:
                        "https://api.twitter.com/1.1/statuses/update.json")
                    let postRequest = SLRequest(forServiceType:
                        SLServiceTypeTwitter,
                        requestMethod: SLRequestMethod.POST,
                        URL: requestURL,
                        parameters: message)

                    postRequest.account = twitterAccount
                    postRequest.addMultipartData(data, withName: "media", type: nil, filename: nil)

                    postRequest.performRequestWithHandler({
                        (responseData: NSData!,
                        urlResponse: NSHTTPURLResponse!,
                        error: NSError!) -> Void in
                        if let err = error {
                            println("Error : \(err.localizedDescription)")
                        }
                        println("Twitter HTTP response \(urlResponse.statusCode)")

                    })
                }
            }
            else
            {
                // do what you want here

            }
    })
}

I've put a tutorial on my blog with the corresponding project in GitHub that illustrates using SLRequest so that animated GIFs are supported...you can see it here: http://www.iosinsight.com/twitter-integration-with-swift/

Note: This code and the Blog post are updated based on comment from maml regarding using simply "update" instead of deprecated "update_with_media".

  • don't use update_with_media, it's been [deprecated](https://dev.twitter.com/rest/reference/post/statuses/update_with_media). – maml Aug 20 '15 at 01:37
  • 1
    Hey thanks for the heads up on that. I'll update the snippet and have updated the sample code in my Github. Cheers! – Lawrence MacFadyen Aug 21 '15 at 11:10