How to set URLSession Swift 3

2019-09-20 01:25发布

问题:

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