2015-11-12 47 views
0

我有迅速2個窗口,一個是像其發送到NSURLConnection.sendAsynchronousRequest得到認證的服務器的登錄對話框。一旦得到迴應,窗口應該關閉。線程+多窗口導致奇怪的錯誤

當我關閉窗口(無論是從登錄窗口類或主窗口類)我得到這些錯誤:

This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.

我已經試過的後臺線程等所有的方式,但我認爲這個問題是因爲我已經關了爲什麼非同步NSURLConnection的請求仍懸窗。

我的代碼來發送從登錄窗口中的異步請求:

dispatch_async(dispatch_get_main_queue(), { 
      let queue:NSOperationQueue = NSOperationQueue() 
      NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
       var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil 
       let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary 
       let result: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)! 

       let expectedString = "special auth string"! 
       if(result == expectedString) { 
        self.callback.loginOK() 
       } else { 
        self.output.stringValue = result 
       } 
       return 
      }) 
     }) 

類的回調構件是派生它,我然後從主應用程序關閉使用loginVC.view.window?.close()登錄窗口的父視圖位指示窗口。這會導致錯誤。

回答

1

的問題是,NSURLConnection.sendAsynchronousRequest總會在輔助線程中運行,因此它的回調會從輔助線程,儘管你從主線程顯式調用它被調用。 你並不需要包裝NSURLConnection.sendAsynchronousRequest在主線程,而不是你的包「self.callback.loginOK()」使用dispatch_async,以確保沒有用戶界面相關操作發生在輔助線程在主線程中運行。像這個 -

let queue:NSOperationQueue = NSOperationQueue() 
      NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in 
       var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil 
       let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary 
       let result: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)! 

       dispatch_async(dispatch_get_main_queue() { 
       let expectedString = "special auth string"! 
       if(result == expectedString) { 
        self.callback.loginOK() 
       } else { 
        self.output.stringValue = result 
       } 
       }) 

       return 
      })