NSURLSession with Token Authentication

前端 未结 3 1454
粉色の甜心
粉色の甜心 2020-12-25 08:47

I have the following code in my iOS project and I want to convert to use NSURLSession instead of NSURLConnection. I am querying a

3条回答
  •  清歌不尽
    2020-12-25 09:24

    You can rewrite it using NSURLSession as follows

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
        NSString *token ; //GET THE TOKEN FROM THE KEYCHAIN
    
        NSString *authValue = [NSString stringWithFormat:@"Token %@",token];
    
        //Configure your session with common header fields like authorization etc
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        sessionConfiguration.HTTPAdditionalHeaders = @{@"Authorization": authValue};
    
        NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
    
        NSString *url;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            if (!error) {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                if (httpResponse.statusCode == 200){
                    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];
    
                    //Process the data
                }
            }
    
        }];
        [task resume];
    

提交回复
热议问题