The Swift Coder
The Swift Coder

Reputation: 442

CompletionHandler Behavior on Main vs Background thread

Does the thread from which a method is being used matter in terms of completionHandlers? When running on the Main thread, I have no problems; the (data) in completionHandler is called and thus the function's completionHandler within that.

The following is my code:

  static func getInfo(user: User,completion: (([String:String]) -> Void)? = nil){
      
       print(user.apiUid)
       var enrolledCourses: [String:String] = [:]
       
       NetworkingManager.staticGeneralRequest(withEndpoint: someURL, oauthToken: user.oauth_token, oauthTokenSecret: user.oauth_token_secret) { (data) in
           let decodedData: [String:String] = data.getData()
           completion?(decodedData)
       }
     
   }

//NOTE: According to the compiler, 
//the use of an optional completionHandler means that it's `@escaping` by default.

Is this an issue pretaining to threading, and what are some best practices to ensure that code works well across threads?

Upvotes: 0

Views: 242

Answers (1)

sonle
sonle

Reputation: 8995

Your closure was deallocated before you get the response. Adding @escaping like this: static func getInfo(user: User, completion: @escaping (([String:String]) -> Void)? = nil) to keep it in scope.

Upvotes: 1

Related Questions