使用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和参数以发送直接消息时,最终导致App崩溃。下面的错误消息,我不知道为什么。任何帮助表示赞赏。
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:]:无法识别 选择器发送到实例0x60800023d200 2018-09-14 14:08:55.706728 + 0200 6WCCompanion [35050:15292775] ***终止应用 由于未捕获的异常“ NSInvalidArgumentException”,原因: '-[__ TtGCs26_SwiftDeferredNSDictionarySSP__ stringByAddingPercentEncodingWithAllowedCharacters:]:无法识别 选择器发送到实例0x60800023d200'