无法设置URLRequest授权标头 [英] Can't set URLRequest Authorization Header

查看:256
本文介绍了无法设置URLRequest授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

我的setAuthorizationHeader >

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


推荐答案

在执行String插值之前,您不会解包String变量,因此将可选字符串描述传递给forHTTPHeaderField。 检查提案:SE-0054。只要确保你安全地解开你的可选使用如果let:

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

这篇关于无法设置URLRequest授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆