我需要帮助在我的 API 代码中实现持有者令牌,但我不知道如何:(



我为我的API编写了代码,但我没有为Bearer Token编写代码,因为我不知道如何正确地完成它,因为我是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",
]

相关内容

最新更新