gpt4 book ai didi

ios - 如何将 header 添加到 dataTaskWithUrl?

转载 作者:IT王子 更新时间:2023-10-29 05:26:12 26 4
gpt4 key购买 nike

我有一个dataTaskWithUrl:

        var headers: NSDictionary = ["X-Mashape-Key": "my-secret-key" , "Accept" : "application/json"]
var stringUrl = "https://restcountries-v1.p.mashape.com/all"
stringUrl = stringUrl.stringByReplacingOccurrencesOfString(" ", withString: "+")
let url = NSURL(string: stringUrl)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary{

println(jsonResult)

}else{
println("error")
}

})

task.resume()

我想为我的任务添加标题。

换句话说,我想将此代码转换为 swift:

NSDictionary *headers = @{@"X-Mashape-Key": @"my-secret-key", @"Accept": @"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:@"https://restcountries-v1.p.mashape.com/all"];
[request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
}];

我是数据请求的新手。我不了解 Objective C 代码,但在查看该代码时我做出了猜测。我需要使用标题,因为如果我只是尝试去 https://restcountries-v1.p.mashape.com/all直接,我得到一个错误。我从这个网站收到了 objective-c 代码:https://www.mashape.com/fayder/rest-countries-v1 .非常感谢在正确方向上提供的任何帮助。

谢谢

最佳答案

更新 Swift 4+:

let httpUrl = "http://...."
guard let url = URL(string: httpUrl) else {
return
}
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("my-secret-key", forHTTPHeaderField: "X-Mashape-Key")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

}
task.resume()

旧帖:

如果要使用dataTask

    var stringUrl = "https://restcountries-v1.p.mashape.com/all"
stringUrl = stringUrl.stringByReplacingOccurrencesOfString(" ", withString: "+")
let url = NSURL(string: stringUrl)
let session = NSURLSession.sharedSession()
var muableRequest = NSMutableURLRequest(URL: url!)
muableRequest.setValue("application/json", forHTTPHeaderField: "Accept")
muableRequest.setValue("my-secret-key", forHTTPHeaderField: "X-Mashape-Key")

let task = session.dataTaskWithRequest(muableRequest, completionHandler: { (data, response, error) -> Void in
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil){

println(jsonResult)

}

})
task.resume()

关于ios - 如何将 header 添加到 dataTaskWithUrl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31799232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com