0

我已经使用 Swift 向 Slack 发布了一些内容,使用 Webhook 作为 POST 请求,但收到类似的错误

interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

在行中var request = ...。谁能告诉我为什么会出现这样的错误?谢谢!!:D

(“此处的 Webhook URL”指的是真正正确的 URL,但发布此问题时,我只是将其替换为“此处的 Webhook URL”。)

import UIKit
import XCPlayground

let str = "payload={'channel': '#test', 'username': 'webhookbot', 'text': 'This is posted to #test and comes from a bot named webhookbot.', 'icon_emoji': ':ghost:'}"
let strData = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData

var request = NSMutableURLRequest(URL: NSURL(string: "Webhook URL here")!, cachePolicy: cachePolicy, timeoutInterval: 2.0)

request.HTTPMethod = "POST"
request.HTTPBody = strData

var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
let results = NSString(data:data!, encoding:NSUTF8StringEncoding)
4

1 回答 1

1

您还应该使用可选绑定来解包数据

if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) {
    let results = NSString(data:data, encoding:NSUTF8StringEncoding)
}

您还可以尝试在同步请求中记录错误,如下面的代码。

所以你的最终代码应该是这样的

import UIKit
import XCPlayground

let str = "payload={'channel': '#test', 'username': 'webhookbot', 'text': 'This is posted to #test and comes from a bot named webhookbot.', 'icon_emoji': ':ghost:'}"
let strData = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData

if let url = NSURL(string: "Your Webhook Url")
{
    var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 2.0)

    request.HTTPMethod = "POST"
    request.HTTPBody = strData

    var error : NSError? = nil
    if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: &error) {
       let results = NSString(data:data, encoding:NSUTF8StringEncoding)
    }
    else
    {
        println("data invalid")
        println(error)
    }
}
else {
    println("url invalid")
}
于 2015-02-02T03:17:04.780 回答