简体   繁体   中英

Notifying main UI thread from background thread in Swift 4

I'm doing some communication work on a background thread, which I start like so:

    self.thread = Thread(target: self, selector: #selector(threadMain), object: nil)
    self.thread?.start()

...

    func threadMain() {
       ...
    }

threadMain is invoked correctly and the processing rolls as it should. The last code sequence on threadMain is the notification of the main thread via externally provided callback "onComplete", which I wanted to do like so:

    print("leaving thread")
    DispatchQueue.main.async {
       self.onComplete?(CommunicationCallbackParams(errorCode: 
            self.errorCode, commState: self.commState, redirectUrl: self.redirectUrl))
    }

However, the code inside the closure is never called. If I remove the "DispatchQueue.main.async" wrap it works, but I notify on non-UI-thread level. What might go wrong here?

The same principle is working fine in Objective C...

The most obvious thing is that you're calling self.onComplete with optional chaining. If onComplete is nil, that code won't get called. However, you say that it does get called if you don't wrap it in a call to DispatchQueue.main.async .

Oh, found the solution. I was calling the class from XCTest using a semaphore in order to wait for the result:

    let semaphore = DispatchSemaphore.init(value:0)
    let _ = Communication(url: "<some url>") { (result) in
        print("Current thread is main thread: \(Thread.isMainThread)")
        print(result)
        semaphore.signal()
    }
    semaphore.wait()

That semaphore pattern must have blocked the notification. Once I changed it to expectations, it worked fine.

    let exp = expectation(description: "\(#function)\(#line)")
    let _ = Communication(url: "<some url>") { (result) in
        print("Current thread is main thread: \(Thread.isMainThread)")
        print(result)
        exp.fulfill()
    }
    waitForExpectations(timeout: 60, handler: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM