iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – URLSession没有在标题swift 4中传递’Authorization’键大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在URLrequest的标头中传递授权密钥.但是在服务器端没有收到密钥.从邮递员工作正常时调用相同的API.标头中的任何其他键工作正常,甚至授权密钥在服务器端也可见.

这是我的代码

let headers = [
    "authorization": "token abcd"
]

var request = URLrequest.init(url: NSURL(String:
    "http://127.0.0.1:7000/api/chAnnels?filter=contributed")! as URL)
request.httpR_42_11845@ethod = "GET"
request.allhttpHeaderFields = headers
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = headers
let session = URLSession.init(configuration: config)

let dataTask = session.dataTask(with: request,completionHandler: { (data,response,error) -> Void in
    if (error != nil) {
        print(error ?? "")
    } else {
        let httpResponse = response as? httpURLResponse
        print(httpResponse ?? "")
    }
})

正如您所看到的,我尝试在会话配置和请求中设置令牌,但没有一个正在工作.

解决方法

@H_673_16@ 这似乎有效:

// Set the security header
private var credentials: String {
    return "\(participantId):\(password)"
}

private var basicAuthHeader: String {
    return "Basic \(credentials)"
}

func getSetTings(participantId: Int,password: String) -> Bool {

    self.participantId = participantId
    self.password = password

    let path = "/setTings/\(participantId)"
    guard let url = URL(String: "\(BASE_URL)\(path)") else {
        Log.e("Invalid URL String,Could not convert to URL")
        return false
    }

    var urlrequest = URLrequest(url: url)
    urlrequest.SETVALue("application/json",forhttpHeaderField: "Content-Type")
    urlrequest.SETVALue(basicAuthHeader,forhttpHeaderField: "Authorization")
    urlrequest.SETVALue(APP_file_name,forhttpHeaderField: "User-Agent")

    // This is a synchronous wrapper extension around URLSession.dataTask()
    let (data,error) = URLSession.shared.synchronousDataTask(with: urlrequest)
    // Process the result...
}

注意:我的同事写的代码.谢谢约翰

大佬总结

以上是大佬教程为你收集整理的ios – URLSession没有在标题swift 4中传递’Authorization’键全部内容,希望文章能够帮你解决ios – URLSession没有在标题swift 4中传递’Authorization’键所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。