简体   繁体   中英

How to POST direct message using Twitter REST API in SWIFT 4

I want to implement to send direct message to my twitter friends using Twitter REST API. I am getting all my friends id and put invite button for sending a message from my app.

Following is the function call I am using -

func sendInviteMessage(_ client: TWTRAPIClient, recepientID: String){

        let statusesShowEndpoint = " https://api.twitter.com/1.1/direct_messages/events/new.json"
        let params = ["recipient_id": recepientID,"message_data":"Hello","type":"message_create"]
        var clientError : NSError?

        let request = client.urlRequest(withMethod: "POST", urlString: statusesShowEndpoint, 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)")
            }
        }

    }

When I tap invite button it gives me unsupported url response.

params is wrong. And you can use MutableURLRequest.

https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event#example-request

let params = [
              "event": [
                "type":"message_create",
                "message_create": [ 
                  "target": ["recipient_id": recepientID],
                  "message_data": ["text": "Hello"]
                ]
              ]
            ]
var request = client.urlRequest(withMethod: "POST", 
                                 urlString: statusesShowEndpoint, 
                                parameters: nil, 
                                     error: &clientError)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM