DispatchQueue.main.sync returning exc_bad_instruction Swift 3

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)
    let request = NSMutableURLRequest(url: URL(string: urlStr)!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 20)
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = 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{
               = jsonArray
                        if let jsonDict:NSDictionary = json as? NSDictionary{
                   = [jsonDict]
    }else {
        result.message = self.error!.debugDescription as NSString?

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


  • 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: {
            print("main thread")