How to set URLSession Swift 3

谁都会走 提交于 2019-12-13 04:06:37

问题


Hey having trouble with Swift 3. I have the following code:

public var urlSession : URLSession?
self.urlSession = URLSession(configuration: URLSessionConfiguration.default,
            delegate: self,
            delegateQueue: OperationQueue.main)

I am getting the following error message: "URLSession produces (), not the expected contextual result type URLSession?"

What am I doing wrong here?


回答1:


My I ask your URLSession functions?

Maybe problem in your code is like:

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

and :

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

so instead of:

func URLSession(session:

do this:

func urlSession(_ session:

final will be like:

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()
    }
}

If its not a solution for your problem please update your question with more code. ✌️




回答2:


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()


来源:https://stackoverflow.com/questions/39634475/how-to-set-urlsession-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!