2015-05-18 57 views
0

我有一個NSOperation子類具有以下main功能:的NSOperation與sendAsynchronousRequest completionBlock

override func main() { 
    if self.cancelled { 
     return 
    } 

    var stringResponse: String! 
    var urlString: String! 
    if self.arduinoConnection.arduinoHTTPPort == 80 { 
     urlString = String(format: "http://%@/arduino/%@/%i/", arguments: [self.arduinoConnection.arduinoAddress, self.arduinoConnection.pinType.lowercaseString, self.arduinoConnection.arduinoPin]) 
    } else { 
     urlString = String(format: "http://%@:%i/arduino/%@/%i/", arguments: [self.arduinoConnection.arduinoAddress, self.arduinoConnection.arduinoHTTPPort, self.arduinoConnection.pinType.lowercaseString, self.arduinoConnection.arduinoPin]) 
    } 
    let url = NSURL(string: urlString) 
    let request = NSURLRequest(URL: url!) 
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in 
     println(NSString(data: data, encoding: NSUTF8StringEncoding)) 
     stringResponse = NSString(data: data, encoding: NSUTF8StringEncoding) as! String 

     if (stringResponse == "") { 
      self.arduinoConnection.state = .Failed 
      self.arduinoConnection.switchState = false 
      self.arduinoConnection.statusText = "Failed To Connect" 
     } else { 
      self.arduinoConnection.state = .Downloaded 
      if (stringResponse == "0") { 
       self.arduinoConnection.state = .Downloaded 
       self.arduinoConnection.switchState = false 
       self.arduinoConnection.statusText = "Connected" 
      } else if (stringResponse == "1") { 
       self.arduinoConnection.state = .Downloaded 
       self.arduinoConnection.switchState = true 
       self.arduinoConnection.statusText = "Connected" 
      } 
     } 
    } 
} 

我操作的狀態是finishedNSURLConnection.sendAsynchronousRequest的完成處理程序實際上是毀了。如何使NSOperation等到NSURLConnection.sendAsynchronousRequest的完成處理程序發生火災?

+0

該操作已經在後臺線程上。因此,使呼叫同步不是異步的。它正在完成的原因是因爲該線程上的運行循環已經完成執行。你需要保持它在該線程上執行。 (你可以搞砸東西,這樣你就不需要這個了,但是讓它同步是最簡單的解決方案)。 – Fogmeister

回答

0

您應該覆蓋start而不是main。您必須手動觸發isExecutingisFinished的通知。 Documentation here

+0

'isExecuting'和'isFinished'是隻讀屬性,如https://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/index.html#//apple_ref/occ/instm/NSOperation/start –

+0

的確如此。你可以繼承'NSOperation'並讓它們讀/寫,你可以在這裏看到:http://stackoverflow.com/questions/24109701/nsoperation-property-overrides-isexecuting-isfinished – Dima

相關問題