我有以下代码:

func downloadItems() {

    let url: NSURL = NSURL(string: urlPath)!
    var session: URLSession!
    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    let task = session.dataTask(with: url as URL)

    task.resume()

}


这来自在线的旧项目,Swift给了我这个错误代码:


  “ URLSession”生成“()”,而不是预期的上下文结果类型“ URLSession!”。


我发现其他人在Stock Overflow上对此提出了疑问,但是所有答案都是针对较早版本的Swift的,并导致其他错误。

这是我发现的其他问题:

How to set URLSession Swift 3

URLSession error

最佳答案

var request = URLRequest(url: URL(string: urlPath!))
request.httpMethod = "GET"
task1 = URLSession.shared.dataTask(with: request) { data, response, error

in guard let data = data, error == nil else {

// check for fundamental networking error

   print("error=\(error)")

 return

}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {


   // check for http errors

   print("statusCode should be 200, but is \(httpStatus.statusCode)")

   print("response = \(response)")

}

let json=JSON(data: data);

self.json=json;

self.parse(json: json)

}

task1.resume()

关于ios - URLSession错误Swift 3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42044764/

10-12 14:35