无法设置URLRequest授权标头

时间:2016-09-19 23:07:56

标签: ios swift cocoa swift3 ios10

自从swift 3更新后,我将我的请求从NSMutableURLRequest更改为URLRequest。之后,由于无效的凭据问题,我的所有请求都停止了。已经尝试过搜索一切。我的服务和以前一样继续,并且从请求模拟器测试了我的请求并且运行良好。

let url : NSString = "http://url.service.com/method?param=\(name)" as NSString

var request = URLRequest(url: URL(string: url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)!)!)
request.httpMethod = "POST"
request.setAuthorizationHeader()

URLSession.shared.dataTask(with: request) {data, response, err in

    do {

        //something

    } catch let error1 as NSError {
        //something
    }

}.resume()

我的setAuthorizationHeader()扩展程序

extension URLRequest {

    mutating func setAuthorizationHeader(){

        let data = "user:password".data(using: String.Encoding.utf8)

        let base64 = data?.base64EncodedString(options: [])
        setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
    }
}

1 个答案:

答案 0 :(得分:1)

在执行String插值之前,您没有展开String变量,因此将可选字符串描述传递给forHTTPHeaderField。 Check Proposal: SE-0054.如果让:

,请确保安全地打开您的可选项
if let base64 = data?.base64EncodedString(options: []) {
    setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
}