top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to make web request to fetch JSON data in SWIFT

0 votes
1,299 views

Here i am struggling to fetch json data from web service in SWIFT. So, i am looking for some idea to do this.

posted Aug 13, 2014 by Manjunath

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

To call web request and to fetch JSON data.

let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
    let url: NSURL = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        println("Task completed")
        if(error) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        if(err != nil) {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")
        }
        let results: NSArray = jsonResult["results"] as NSArray
        dispatch_async(dispatch_get_main_queue(), {
            self.tableData = results
            self.appsTableView!.reloadData()
            })
        })
answer Aug 13, 2014 by Raju
The answer is right, although it is missing "task.resume()" at the end, and it has some errors compiling with Swift v1.2. I made some brief changes so one can just copy and paste the code to try it.

        var escapedSearchTerm = "mario"
        let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
        let url:NSURL! = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
            println("Task completed")
            if((error) != nil) {
                // If there is an error in the web request, print it to the console
                println(error.localizedDescription)
            }
            var err: NSError?
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
            if(err != nil) {
                // If there is an error parsing JSON, print it to the console
                println("JSON Error \(err!.localizedDescription)")
            }
            let results: NSArray = jsonResult["results"] as! NSArray
            dispatch_async(dispatch_get_main_queue(), {
                println(results)
                /*self.tableData = results
                self.appsTableView!.reloadData()*/
            }) })
        task.resume()

Also uploaded it to Github: https://github.com/izeta/Swift-JSON-Web-Requests
Similar Questions
+1 vote

How to declare single parameter which accept multiple values.

+1 vote

How to use default values for parameter in function. What will happens when value is not passed for a default parameters.

0 votes

I am facing situation to use external parameter name to a function parameter name .. How to achieve this

0 votes

Is it possible to set multiple return type for function in SWIFT. If yes please provide me syntax .

0 votes

How to set return type for function in SWIFT.

...