Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)     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 } 
like image 431
Rodrigo Costa Avatar asked Oct 20 '16 12:10

Rodrigo Costa


People also ask

What is DispatchQueue main async in Swift?

You've scheduled a body of work to be done but you also don't want to block what you're doing now. To summarize, DispatchQueue. async allows you to schedule work to be done using a closure without blocking anything that's ongoing. In most cases where you need to dispatch to a dispatch queue you'll want to use async .

Is DispatchQueue main serial?

DispatchQueue. main (the main queue) is a serial queue. sync and async do not determine serialization or currency of a queue, but instead refer to how the task is handled. Synchronous function returns the control on the current queue only after task is finished.

What is DispatchQueue Global () async?

There are background threads for heavy tasks. DispatchQueue. global() runs these kind of tasks in background threads. You can tell the queue about how important your task is, so that DispatchQueue can prioritize your task. You can do this by providing Quality-of-Service information.


2 Answers

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")     } }) 
like image 189
Max Pevsner Avatar answered Oct 09 '22 02:10

Max Pevsner


Maybe it's because you are trying to DispatchQueue.main.sync from the Main thread. You can check if you are already in the main thread like:

if Thread.isMainThread {   // do stuff } else {   DispatchQueue.main.sync {     // do stuff   } } 
like image 45
rockdaswift Avatar answered Oct 09 '22 02:10

rockdaswift