我有一個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"
}
}
}
}
我操作的狀態是finished
前NSURLConnection.sendAsynchronousRequest
的完成處理程序實際上是毀了。如何使NSOperation
等到NSURLConnection.sendAsynchronousRequest
的完成處理程序發生火災?
該操作已經在後臺線程上。因此,使呼叫同步不是異步的。它正在完成的原因是因爲該線程上的運行循環已經完成執行。你需要保持它在該線程上執行。 (你可以搞砸東西,這樣你就不需要這個了,但是讓它同步是最簡單的解決方案)。 – Fogmeister