zya zya - 10 days ago 5
iOS Question

URLSession & JSONSerialization Swift 3

Before you read this, please understand that I'm somewhat a beginner with Swift and I'm trying to learn. I've browse through some sites in hope of getting answer but I either can't find or do it incorrectly.. I've been following this tutorial but this is old and not updated >>Tutorial I followed<<

I also tried to modified some to swift 3 - though I probably didn't do it right.

How do I exactly do the URLSession correctly? I get this error:


invalid conversion from throwing function of type'(_, _, _) throws ->
Void' to non-throwing function type


for this line below:


let task : URLSessionDataTask = session.dataTask(with: request,
completionHandler: {data, response, error -> Void in


and for the variable "jsonDict" - I get error that I have


extra arg 'error' in call.


Thanks in advance

var urlString:String = ("http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN "+stringQuotes+"&format=json&env=http://datatables.org/alltables.env").addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

var url : URL = URL(string: urlString)!
var request: URLRequest = URLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

let task : URLSessionDataTask = session.dataTask(with: request, completionHandler: {data, response, error -> Void in

if((error) != nil) {
println(error.localizedDescription)
}
else {
var err: NSError?

var jsonDict = try JSONSerialization.JSONObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers, error: &err) as NSDictionary
if(err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
else {
var quotes:NSArray = ((jsonDict.objectForKey("query") as NSDictionary).objectForKey("results") as NSDictionary).objectForKey("quote") as NSArray
DispatchQueue.main.async(execute: {
.default.post(name: Notification.Name(rawValue: kNotificationStocksUpdated), object: nil, userInfo: [kNotificationStocksUpdated:quotes])
})
}
}
})
task.resume()
}

Answer

Please find the updated code for Swift 3.0

var urlString:String = ("http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol IN "+stringQuotes+"&format=json&env=http://datatables.org/alltables.env").addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

        let url : URL = URL(string: urlString)!
        let request: URLRequest = URLRequest(url:url)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        let task = session.dataTask(with: request) { (data, response, error) in

            if(error != nil){
                print(error?.localizedDescription ?? "")
            }
            else{
                do{
                    let jsonDict:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                    let quotes:NSArray = ((jsonDict.object(forKey: "query") as! NSDictionary).object(forKey: "results") as! NSDictionary).object(forKey: "quote") as! NSArray
                    print(quotes)

                }
                catch{
                    print(error.localizedDescription)
                }
            }
        };
        task.resume()

Note: I haven't tested the code . Since you haven't specified the arguments of URL

Comments