NSOperation 与 sendAsynchronousRequest completionBlock

NSOperation with sendAsynchronousRequest completionBlock

我有一个具有以下 main 函数的 NSOperation 子类:

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"
            }
        }
    }
}

NSURLConnection.sendAsynchronousRequest 的完成处理程序实际被破坏之前,我的操作状态是 finished。如何让 NSOperation 等到 NSURLConnection.sendAsynchronousRequest 的完成处理程序触发?

您应该覆盖 start 而不是 main。您必须手动关闭 isExecutingisFinished 的通知。 Documentation here.