NSURLSession with Token Authentication

前端 未结 3 1446
粉色の甜心
粉色の甜心 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" }
    

提交回复
热议问题