NSURLSession with Token Authentication

前端 未结 3 1427
粉色の甜心
粉色の甜心 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:05

    Set the Authorization header on your URLSession configuration, or directly on your request.

    Be advised that Apple says you "should not" attempt to modify the Authorization header in your URLSession configuration:

    An URLSession object is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers:

    • Authorization

    • ...

    It is, however, possible. If you want to do this, ensure that you set the header configuration before you create the URLSession. It's not possible to modify headers on an existing URLSession.

    Here is a Swift playground that shows different scenarios:

    import Foundation
    
    // 1: Wrong -- mutating existing config for existing URLSession is no-op
    
    var session = URLSession.shared
    session.configuration.httpAdditionalHeaders = ["Authorization": "123"]
    
    let url = URL(string: "https://postman-echo.com/get")!
    
    session.dataTask(with: url) { (data, resp, err) in
        if let data = data {
            let str = String(bytes: data, encoding: .utf8)!
            let _ = str
        }
    }.resume() // no authorization header
    
    // 2: Setting headers on an individual request works fine.
    
    var request = URLRequest(url: url)
    request.addValue("456", forHTTPHeaderField: "Authorization")
    session.dataTask(with: request) { (data, resp, err) in
        if let data = data {
            let str = String(bytes: data, encoding: .utf8)!
            let _ = str
        }
    }.resume() // "headers": { "authorization": "456" }
    
    // 3: You can set headers on a new URLSession & configuration
    
    var conf = URLSessionConfiguration.default
    conf.httpAdditionalHeaders = [
        "Authorization": "789"
    ]
    session = URLSession(configuration: conf)
    
    session.dataTask(with: url) { (data, resp, err) in
        if let data = data {
            let str = String(bytes: data, encoding: .utf8)!
            let _ = str
        }
    }.resume() // "headers": { "authorization": "789" }
    
    0 讨论(0)
  • 2020-12-25 09:13

    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()
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
提交回复
热议问题