使用session从url获取Json

时间:2017-11-05 12:44:58

标签: ios json swift api

我正在使用xcode 9 beta 5.我试图解析网址。虽然基于url维护会话代码会给出语法错误。

 static func fetchFeatureApp(){
        let urlString="http://ebmacs.net/ubereats/Api/all_product?id=1"
        URLSession.shared.dataTask(with: NSURLRequest(url: urlString)) { (data, responce, error) in
            if error!=nil
            {
                print(error)
                return

            }
        }.resume()
    }

image description here

URLSession.shared.dataTask(with: NSURLRequest(url: urlString)) { (data, responce, error) in

这行代码给出了错误

  

无法转换类型'字符串'的值预期参数类型' URL'   如何纠正这个

如何删除此错误? 我访问了这个link

2 个答案:

答案 0 :(得分:0)

URLRequest需要URL而不是String,这是错误消息所指出的内容。

let urlString = "http://ebmacs.net/ubereats/Api/all_product?id=1"
let url = URL(string: urlString)!
URLSession.shared.dataTask(with: URLRequest(url: url)) { (data, responce, error) in ...

访问过的链接会从字符串中清楚地创建URL

但实际上,您不需要URLRequest来获取简单的GET请求,只需通过URL

let url = URL(string: "http://ebmacs.net/ubereats/Api/all_product?id=1")!
URLSession.shared.dataTask(with: url) { (data, responce, error) in ...

答案 1 :(得分:0)

嗨,这是我最喜欢的urlsession下载代码,

var request = URLRequest(url: URL(string: "Your URL String")!)

request.httpMethod = "POST"
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
     let parsedData = try JSONSerialization.jsonObject(with: data!) //if you want to convert to Json  
 }.resume()