[英]I need help implementing Bearer Token in my API code but I don't know how :(
我为我的 API 编写了代码,但我没有为承载令牌编写代码,因为我不知道如何正确执行,因为我是 swift 的新手 :) 所以如果有人可以帮助我或引用我的链接关于如何做到这一点:)
这就是我在代码中的全部内容,但它不起作用:(
let headers = [
"content-type": "application/json",
"authorizetoken": "NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
"cache-control": "no-cache",
]
}
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 120)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
import Foundation
func ApiCall(urlString:String,completion:@escaping (_ data:Data?,_ error:Error?)->Void) {
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.allHTTPHeaderFields = [
"content-type": "application/json",
"authorizetoken": "NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
"cache-control": "no-cache",
]
//// you can write "Bearer" if you are requesting url as a user from server like its only use for you
////if not only for you but for a group of users or for an app you shold only wirte the token string
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { return completion(nil,error) }
guard let data = data, let response = response else { return }
let yourdata = data
completion(data,nil)
print(data,response)
// handle data
}.resume()
}
你可以像这样使用它
let data = ApiCall(urlString:"http:example.com") { data, error in
if let _data = data {
// handle your data here
}
if let err = error {
// handle your error here
}
}
您需要更新您的 allHTTPHeaderFields
request.allHTTPHeaderFields = [
"content-type": "application/json",
"authorizetoken": "Bearer NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
"cache-control": "no-cache",
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.