在 Swift 中调用 Slack Webincoming 挂钩但得到 "interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

Call Slack Webincoming hook in Swift but get "interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

我已经使用 Swift 到 post Slack 使用 Webhook 作为 POST 请求的东西,但是得到了类似

的错误

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

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

("Webhook URL here"指的是一个真正的URL,但是当post这个问题我只是用"Webhook URL here"替换它。)

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)

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

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