0

I am trying to use swift to request an API and then parse the data and use it as I see fit. I have been able to request the API but I am confused about the process.

In Javascript the following steps are involved:

  1. Make a HTTP Request ( GET, POST etc )
  2. You get data back in JSON form
  3. Create a local variable and save the incoming JSON
  4. If the incoming JSON is an array then use a for loop to loop through it.
  5. If the JSON is a single object then simply use the "myObject.value" technique to extract data

Below is the code for my Swift HTTP request. I am getting the data back and it is being saved within "jsonResult" but I can seem to parse the data.

Can anyone explain what the are main steps involved in making HTTP requests and parsing the data in swift. And when to use NSArray and NSDictionary?

 //: Playground - noun: a place where people can play

 import UIKit
 import XCPlayground // add this in


 XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
 let url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk"

 NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { data, response, error in
 // Handle result

  println(NSString(data: data, encoding: NSUTF8StringEncoding))
  //HOW TO PARSE THE DATA

  }.resume()

The println is giving the following OutPut:

enter image description here

Any help will be greatly appreciated.

Skywalker
  • 4,984
  • 16
  • 57
  • 122
  • There's already a lot of similar questions with answers on SO. You can search for `NSJSONSerialization` for example. Or use a third-party library like SwiftyJSON. – Eric Aya Jun 11 '15 at 10:27
  • Another good option is JSONModel ( https://github.com/icanzilb/JSONModel/) for parsing JSON response from server side. However, it is available in Objective-C. You need to go through http://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift to user this Objective-C third party library with your swift code. – Sauvik Dolui Jun 11 '15 at 11:26

0 Answers0