具有令牌认证的NSURLSession

问题描述 投票:10回答:3

我在iOS项目中有以下代码,我想转换为使用NSURLSession而不是NSURLConnection。我正在查询使用基于令牌的REST API方案的HTTP Authentication,但找不到如何执行此操作的示例。

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
                                   }
                               }

                           }];
}
ios objective-c ios7 nsurlsession
3个回答
20
投票

您可以使用NSURLSession如下重写它

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

3
投票

这在Swift中,但是逻辑是相同的:

    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
投票

在URLSession配置上或直接在您的请求上设置Authorization标头。

被告知苹果说您“不应该”尝试modify the Authorization header in your URLSession configuration:

URLSession对象旨在为您处理HTTP协议的各个方面。因此,您不应修改以下标题:

  • 授权

  • ...

但是,有可能。如果要执行此操作,请确保在创建URLSession之前设置标头配置之前。无法修改现有URLSession上的标题。

这里是一个显示不同场景的Swift游乐场:

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" }
© www.soinside.com 2019 - 2024. All rights reserved.