NSURLSession with Token Authentication

℡╲_俬逩灬. 提交于 2019-12-18 10:56:11

问题


I have the following code in my iOS project and I want to convert to use NSURLSession instead of NSURLConnection. I am querying a REST API which uses a token-based HTTP Authentication scheme but I cannot find an example of how to do it.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"Username"];

NSString *token = //GET THE TOKEN FROM THE KEYCHAIN


NSString *authValue = [NSString stringWithFormat:@"Token %@",token];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];


if ([NSURLConnection canHandleRequest:request]){
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [NSURLConnection sendAsynchronousRequest:request queue:self.fetchQueue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

                               if (!connectionError) {
                                   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                                   if (httpResponse.statusCode == 200){
                                       NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];

                                       //Process the data
                                   }
                               }

                           }];
}

回答1:


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];



回答2:


This is in Swift, but the logic is the same:

    let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    let url  = NSURL(string: "some url")

    let request = NSMutableURLRequest(URL: url!)
    request.setValue("value", forHTTPHeaderField: "header field")

    let urlSession = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: NSOperationQueue.mainQueue())


    let dataTask = urlSession.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
    }

    dataTask.resume()


来源:https://stackoverflow.com/questions/20920302/nsurlsession-with-token-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!