线程完成时Swift 2 Button Label文本更改

时间:2016-05-07 02:28:55

标签: xcode multithreading swift2 nsoperation dispatch-async

我正在运行一系列调度,当最后一个调度完成后,我想更改按钮的标签。但是,更改swift并不喜欢在主线程之外进行UI组件更改。有时它有效。有时却没有。奇怪的是,当它没有时,如果我点击断点图标(无论我是否激活所有断点,或禁用,标签会立即根据需要改变。

    @IBAction func runButtonSelected(sender: AnyObject) {
        runButton.setTitle("Stop Run", forState: UIControlState.Normal)
        isRunning = true
        self.run()
    }

    func run() {
    let thread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    NSThread.sleepForTimeInterval(1)
    dispatch_async(thread, {
        NSThread.sleepForTimeInterval(1)
        .           
        .
        .
        .       
        var request = Request(URL: NSURL(string: url+params)!, method: "GET", params: "")
        request.isRequesting = true
        queue.addOperation(request)
        request.threadPriority = 0
        request.completionBlock = {() -> () in
            request.execute()
            NSThread.sleepForTimeInterval(2)
        }
        while request.isRequesting {
            if !request.isRequesting {
                break
            }
        }

        .
        .
        .
        .           
        /* visit user profiles based on match results */
        for (index, profile) in profiles.enumerate() {
            let URL = NSURL(string: "https://www.somewebsite.com/profile/\(profile)")!
            let request = Request(URL: URL, method: "GET", params: "")

            var contentsOfURL = NSString()
            request.isRequesting = true
            queue.addOperation(request)
            request.threadPriority = 0
            request.completionBlock = {() -> () in
                request.execute()   
            }
            NSThread.sleepForTimeInterval(1)
        }

        self.isRunning = false
    })
    let thread2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(thread2, {
        while self.isRunning {
            if !self.isRunning {
                break
            }
        }
        self.runButton.setTitle("Run", forState: UIControlState.Normal)
    })
}

Request.execute

func execute() {
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: URL)
    request.HTTPMethod = self.method
    request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
    self.task = session.dataTaskWithRequest(request) {
        (data, response, error) in
        if error == nil {
            do {
                .
                .
                .
                .                   
                switch self.statusCode {

                case 200:
                    self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
                case 400:
                    print("400: page not found")

                case 404:
                    print("404: page not found")

                case 407:
                    print("407: failed authenticate proxy credentials")

                default:
                    print("unable to get statusCode")

                }
            } catch {
                print(error)
            }
            self.isRequesting = false
        } else {
            print(error)
        }
    }
        self.task.resume()
}

1 个答案:

答案 0 :(得分:0)

由于您希望最后一次调度在其他调度之后对该块执行操作:

void dispatch_async( dispatch_get_main_queue(), dispatch_block_t block);

这将使用与应用程序主线程关联的串行调度队列,而不是像以前那样在后台运行。