如何在SWIFT 4中使用Twitter REST API发布直接消息

时间:2018-08-06 09:06:41

标签: ios swift rest twitterkit

我想实现使用Twitter REST API向我的Twitter朋友发送直接消息。我正在获取所有朋友的ID,并放置了邀请按钮,用于从我的应用发送消息。

以下是我正在使用的函数调用-

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)")
            }
        }

    }

当我点击邀请按钮时,它会给我不支持的网址响应。

1 个答案:

答案 0 :(得分:2)

params是错误的。您可以使用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: [])