DispatchQueue.main.sync returning exc_bad_instruction Swift 3

时间:2016-10-20 12:35:51

标签: ios swift swift3 grand-central-dispatch

I want to display an ActivityIndicatorView in my app, but when I call the sync method from the main thread, the app crashes with the error: exc_bad_instruction (code=exc_i386_invop subcode=0x0) I'm using xcode 8.0 and swift 3

Can someone please help me?

 func POST(endpoint:NSString!,body:NSString!,vc:UIViewController? = nil)->NetworkResult{
    let result = NetworkResult()
    DispatchQueue.main.sync {
        self.displayActivityIndicator(viewController: vc)
    }
    let urlStr = self.url.appending(endpoint as String).appending(self.getHashAutenticacao() as String)
    print(urlStr)
    let request = NSMutableURLRequest(url: URL(string: urlStr)!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20)
    print(request.debugDescription)
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = body.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true)

    // send the request
    var data: NSData!
    do {
        data = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &self.response) as NSData!
    } catch let error1 as NSError {
        self.error = error1
        data = nil
    }
    if let httpResponse = self.response as? HTTPURLResponse {
        result.resultCode = httpResponse.statusCode

        if httpResponse.statusCode == 200{
            if data != nil{
                if data.length > 0{
                    let json = (try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers))
                    if let jsonArray:NSArray = json as? NSArray{
                        result.data = jsonArray
                    }else{
                        if let jsonDict:NSDictionary = json as? NSDictionary{
                            result.data = [jsonDict]
                        }
                    }
                }
            }
        }
    }else {
        result.message = self.error!.debugDescription as NSString?
    }

    DispatchQueue.main.sync {
        self.hideActivityIndicator(viewController: vc)
    }
    return result
}

3 个答案:

答案 0 :(得分:34)

What you are trying to do here is to launch the main thread synchronously from a background thread before it exits. This is a logical error.

You should do it like this:

DispatchQueue.global().async(execute: {
    print("teste")
    DispatchQueue.main.sync{
        print("main thread")
    }
})

答案 1 :(得分:19)

也许是因为您正在尝试从主线程中调用DispatchQueue.main.sync。您可以检查您是否已经在主线程中:

if Thread.isMainThread {
  // do stuff
} else {
  DispatchQueue.main.sync {
    // do stuff
  }
}

答案 2 :(得分:0)

如果你想从主线程读取值,这里有一个方便的函数:

func syncMain<T>(_ closure: () -> T) -> T {
    if Thread.isMainThread {
        return closure()
    } else {
        return DispatchQueue.main.sync(execute: closure)
    }
}

用法:

// we are in BG or Main, does not matter
let value = syncMain {
    // we are in Main for sure
    return ...
}