Search code examples
objective-coauth-2.0afnetworking-3

how do i get refresh token with each request?


I am Communicating with .net api over server and now in api they are using oAuth2. So in ios i have to get refresh token every time i'm making request and in another request i have to pass this token. Its like "bearer TOKEN".I am using AFNetworking in my app. Any idea to get this thing working?.


Solution

  • In AFNetworking3 you will use HEAD request for getting refresh token. And then Fire your actual request on success block.

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headerFields:headerFields success:^(NSURLSessionDataTask *task, __unused id responseObject) {
        if (success) {
            success(task);
            // on success block you can fire your final API with below refresh token
             [manager.requestSerializer setValue:@"Bearer RRFRESH_TOKEN" forHTTPHeaderField:@"Authorization"];
        }
    } failure:failure];
    
    [dataTask resume];
    

    You and also create an operation object to perform both API which is more manageable and flexible.