自从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()
My 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")
}
}
最佳答案
在执行字符串插值并将可选的字符串描述传递给forHTTPHeaderField之前,不能展开字符串变量。Check Proposal: SE-0054.只要确保安全地打开可选的包装,使用if let:
if let base64 = data?.base64EncodedString(options: []) {
setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
}
关于ios - 无法设置URLRequest授权 header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39583393/