如何设置URLSession Swift 3

时间:2016-09-22 08:54:44

标签: ios swift nsurlsession

嘿,我遇到了Swift 3.我有以下代码:

method = typeof(c).GetMethods().FirstOrDefault(m => m.IsGenericMethod &&
                    m.GetParameters()[0].ParameterType.GetGenericTypeDefinition()
                        == typeof(IEnumerable<>));

我收到以下错误消息: “URLSession produce(),而不是预期的上下文结果类型URLSession?”

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

我问你的URLSession功能吗?

您的代码中的问题可能就像:

func URLSession(session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    self.data.append(data as Data)  
}

和:

func URLSession(session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil {
        print("Failed to download data")
    }else {
        print("Data downloaded")
        self.parseJSON()
    }
}

所以代替:

func URLSession(session:

这样做:

func urlSession(_ session:

最终将会像:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    self.data.append(data as Data)  
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil {
        print("Failed to download data")
    }else {
        print("Data downloaded")
        self.parseJSON()
    }
}

如果它不是您问题的解决方案,请使用更多代码更新您的问题。 ✌️

答案 1 :(得分:0)

Swift 3.0

let urlString=  "URL String"
let myUrl = URL(string: urlString);
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "GET";

let task = URLSession.shared().dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
        print(error!.localizedDescription)
        DispatchQueue.main.sync(execute: {
            AWLoader.hide()
        })
        return
    }

    do {

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray 

 if let parseJSON = json{
 print(parseJSON)
 } else {
 AWLoader.hide()
 }
catch{
        AWLoader.hide()
        print(error)
    }
}
task.resume()