Ahmed
Ahmed

Reputation: 1359

main thread is NULL in swift even though I specified running on main thread

I am fetching Contact on myphone Using that code

DispatchQueue.main.async {
        let allowedCharset = CharacterSet
            .decimalDigits
        let store = CNContactStore()
        //store.requestAccess(for: .contacts, complete:() -> ()) { (granted,err) in
        store.requestAccess(for: .contacts) { (granted, err) in
            if let error = err
            {
                print("failed to access",error)
                return
            }
            if (granted)
            {
                print(Thread.current)}

However I found that UI is freezing and I am getting that the current thread is NULL even though I specified it to run on mainThread.

print(Thread.current) =

Upvotes: 0

Views: 176

Answers (1)

Andreas Oetjen
Andreas Oetjen

Reputation: 10209

I guess the problem is that you do some UI updates in the completion handler of store.requestAccess.

The handler - according to Apple's documentation - is not called in the main (UI) thread, but in an worker thread:

The completion handler is called on an arbitrary queue. It is recommended that you use CNContactStore instance methods in this completion handler instead of the UI main thread.

Therefore, if you do some UI stuff in here, you must dispatch those calles again into the main thread.

Upvotes: 3

Related Questions