使用 Swift,我可以使用以下代码毫无问题地发布推文:
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)")
}
}
}
}
}
-
但是,当我更改 urlEndpoint 和参数以发送直接消息时,我最终会在应用程序中崩溃。下面的错误消息&我不知道为什么。任何帮助表示赞赏。
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)")
}
}
}
}
}
我得到的“无法识别的选择器”错误消息是
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] * ** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[_TtGCs26_SwiftDeferredNSDictionarySSP__ stringByAddingPercentEncodingWithAllowedCharacters:]:无法识别的选择器发送到实例 0x60800023d200”