Completion Handler with asyncTask


(Tarik Slimani) #1

I use Alamofire for send a request. I must rescup a token before to load my viewControler. So, I write a function in app controller (func application).

how wait the end of process before to go to view controller because I must rescup a token ?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Thread.sleep(forTimeInterval: 1.5)
let _: Bool = KeychainWrapper.standard.removeObject(forKey: "token")
Helper().alomofireGet(URL: "http://192.168.1.19/app_dev.php/login/app") { JSON in
    print(JSON)
    let token = JSON["csrfToken"].stringValue
    let _: Bool = KeychainWrapper.standard.set(token, forKey: "token")
}
return true

In my classe Helper, I have a function for Alamofire Get.

func alomofireGet(URL: String, onCompletion: @escaping ((_ response: JSON) -> Void)) {
var contentJSON = JSON()
Alamofire.request(URL, method: .get).responseJSON() { (reponse) in
    if reponse.result.isSuccess {
        contentJSON = JSON(reponse.result.value!)
    } else {
        contentJSON = JSON(reponse.result.error!)
    }
    onCompletion(contentJSON)
}

}

Problem : JSON/Token empty -> View Controller -> JSON/Token full My goal is : JSON/Token full -> View Controller


(John McCall) #2

(John McCall) #3

(Jon Shier) #4

Generally, this is more of an app architecture question, not really related to Alamofire, but Alamofire can certainly help out here. Typically you'd make your network calls like normal, and have a RequestRetrier set on your SessionManager instance that is run when your requests fail due to token expiration. That, plus a RequestAdapter to add the token to request in the first place, allow you to completely hide your token updating behind your networking layer and not concern your app launch or view controllers with it. If you do need to show something in particular while a refresh is happening, I suggest you set up some sort of observable (many libraries available) that you trigger while refreshes are occurring, and have the relevant parts of your apps listen to it.