Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading and parsing json in swift

I'm trying to get the JSON from a website and parse it before putting it inside of an iOS view.

Here's my code;

func startConnection(){         let urlPath: String = "http://binaenaleyh.net/dusor/"         var url: NSURL = NSURL(string: urlPath)         var request: NSURLRequest = NSURLRequest(URL: url)         var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)         connection.start()     }      func connection(connection: NSURLConnection!, didReceiveData data: NSData!){         self.data.appendData(data)     }      func buttonAction(sender: UIButton!){         startConnection()     }      func connectionDidFinishLoading(connection: NSURLConnection!) {         var err: NSError         // throwing an error on the line below (can't figure out where the error message is)         var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary     } 

And this is the link for the JSON;

http://binaenaleyh.net/dusor/ 

What am I doing wrong here?

like image 820
Çağdaş Salur Avatar asked Jun 05 '14 16:06

Çağdaş Salur


People also ask

How do I use JSON in Swift?

Convert the JSON string to a Data type. Create an instance of JSONDecoder. Instead of using the CodingKey protocol, there is a property on the JSONDecoder class called keyDecodingStrategy that makes converting a JSON key formatted as snake_case to Swift's preferred camelCase. Nice and easy!

What is Jsonpath parse?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.


2 Answers

These two functions worked for me:

    func getJSON(urlToRequest: String) -> NSData{         return NSData(contentsOfURL: NSURL(string: urlToRequest))     }      func parseJSON(inputData: NSData) -> NSDictionary{         var error: NSError?         var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary          return boardsDictionary     } 
like image 160
Çağdaş Salur Avatar answered Oct 07 '22 08:10

Çağdaş Salur


UPDATE: Swift 4

// Asynchronous Http call to your api url, using URLSession: URLSession.shared.dataTask(with: URL(string: "http://api.site.com/json")!) { (data, response, error) -> Void in     // Check if data was received successfully     if error == nil && data != nil {         do {             // Convert to dictionary where keys are of type String, and values are of any type             let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: Any]             // Access specific key with value of type String             let str = json["key"] as! String         } catch {             // Something went wrong         }     } }.resume() 

Here is how to do it with Swift 2 and NSURLSession:

// Asynchronous Http call to your api url, using NSURLSession: NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in     // Check if data was received successfully     if error == nil && data != nil {         do {             // Convert NSData to Dictionary where keys are of type String, and values are of any type             let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]             // Access specific key with value of type String             let str = json["key"] as! String         } catch {             // Something went wrong         }     } }).resume() 
like image 36
david72 Avatar answered Oct 07 '22 10:10

david72