Search code examples
iosjsonswiftswift-playgroundslack-api

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


I've use Swift to post something to Slack use Webhook as an POST request, but get an error like

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

in the line of var request = .... Can anyone tell me why I get such an error? Thanks!! :D

("Webhook URL here" refers to a real proper URL, but when post this question I just replace it with "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)

Solution

  • You should also use optional binding to unwrap your data

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

    You can also try logging the error in the synchronous request like the code below.

    So your final code should be something like this

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