简体   繁体   中英

How to set URLSession Swift 3

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?

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. ✌️

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM