Can't set URLRequest Authorization Header

若如初见. 提交于 2019-12-25 08:07:22

问题


Since swift 3 update I change my requests from NSMutableURLRequest to URLRequest. After that all my requests stopped worked due invalid credentials problem. Already tried and search everything. My service continue same as before and tested my requests from a request simulator and went fine.

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

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:


You are not unwrapping your String variable before doing the String interpolation and thus passing an Optional string description to forHTTPHeaderField. Check Proposal: SE-0054. Just make sure you safely unwrap your optional using if let:

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


来源:https://stackoverflow.com/questions/39583393/cant-set-urlrequest-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!