Setting parameters for urlRequest with TwitterKit for Direct Message in Swift

229 views Asked by At

With Swift, I am able to post a tweet without a problem using the following code:

func postTweet(tweet : String) {
    if (TWTRTwitter.sharedInstance().sessionStore.hasLoggedInUsers()) {
        var clientError : NSError?
        let session = TWTRTwitter.sharedInstance().sessionStore.session()

        if let userid = session?.userID {

            let client = TWTRAPIClient(userID: userid)
            let urlEndpoint = "https://api.twitter.com/1.1/statuses/update.json"
            let params = ["status": "This works fine."]

            let request = client.urlRequest(withMethod: "POST",
                 urlString: urlEndpoint, 
                 parameters: params, error: &clientError)

            client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
                if connectionError != nil {
                    print("Error: \(String(describing: connectionError?.localizedDescription))")
                }

                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: [])
                    print("json: \(json)")

                } catch let jsonError as NSError {
                    print("json error: \(jsonError.localizedDescription)")
                }
            }
        }
    }
}

-

However, when I change the urlEndpoint and parameters in order to send a Direct Message, I end up getting a crash in the App. Error message below & I can't figure out why. Any help appreciated.

func postDM(tweet : String) {
    if (TWTRTwitter.sharedInstance().sessionStore.hasLoggedInUsers()) {
        var clientError : NSError?
        let session = TWTRTwitter.sharedInstance().sessionStore.session()
        let statusesShowEndpoint = "https://api.twitter.com/1.1/direct_messages/events/new.json"

        // '{"event": {"type": "message_create", "message_create": {"target": {"recipient_id": "RECIPIENT_USER_ID"}, "message_data": {"text": "Hello World!"}}}}'

        let param = [
            "event": [
                "type":"message_create",
                "message_create": [
                    "target": ["recipient_id": "6WCbot"],
                    "message_data": ["text": "\(tweet)"]
                ]
            ]
        ]

        if let userid = session?.userID {

            let client = TWTRAPIClient(userID: userid)
            //let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/update.json"
            //let param = ["status": "Terceiro teste?"]
            //print (param)

            // CRASH HERE
            var request = client.urlRequest(withMethod: "POST", urlString: statusesShowEndpoint, parameters: param, error: &clientError) 

            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpBody = try? JSONSerialization.data(withJSONObject: param, options: [])

            client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
                if connectionError != nil {
                    print("Error: \(String(describing: connectionError?.localizedDescription))")
                }

                do {
                    if data != nil {
                        let json = try JSONSerialization.jsonObject(with: data!, options: [])
                        print("json: \(json)")
                    }

                } catch let jsonError as NSError {
                    print("json error: \(jsonError.localizedDescription)")
                }
            }
        }
    }
}

The "unrecognized selector" error message I get is


2018-09-14 14:08:55.697266+0200 CompanionApp[35050:15292775] -[_TtGCs26_SwiftDeferredNSDictionarySSP__ stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0x60800023d200 2018-09-14 14:08:55.706728+0200 6WCCompanion[35050:15292775] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_TtGCs26_SwiftDeferredNSDictionarySSP__ stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0x60800023d200'

1

There are 1 answers

0
Keyur Faldu On

Please use this format

{ "event": { "type": "message_create", "message_create": { "target": { "recipient_id": "844385345234" }, "message_data": { "text": "Hi, my name is Jon. How can I help?", }, "custom_profile_id": "100001" } } }