JSON Parsing in IOS using SWIFT
Hi!
About JSON!
JSON is a Very light weight framework to transfer data when compare with XML.
JSON in IOS!
Like Android, IOS also can transfer the data very fast and securely in JSOn format.
Today i am going to give an example about how to transfer the JSON data to IOS by using the Brand new SWIFT language.
Step 1:
Create a new ios project using your XCODE. delete the default story board and its ViewController.
Step 2:
On your StoryBoard Place a Table View Controller, on your
CELL change the Identifier name as "cell"
Step 3:
Create a COcoa Touch new class with SubClass of UITableViewController after create the class configure as Custom Class of your StoreBoard Table View Controller.
Sample JSON Data :
{
"Data": [
{
"AccountId": "xxxxxxxxxxxxxxxx",
"AccountName": "xxxxxxxxxxxxxxxx",
"Topic": "xxxxxxxxxxxxxxxx",
"Discipline": "xxxxxxxxxxxxxxxx",
"Source": "xxxxxxxxxxxxxxxx",
"Email": "xxxxxxxxxxxxxxxx",
"PhoneNumber": "xxxxxxxxxxxxxxxx",
"URL": "xxxxxxxxxxxxxxxx"
},
{
"AccountId": "xxxxxxxxxxxxxxxx",
"AccountName": "xxxxxxxxxxxxxxxx",
"Topic": "xxxxxxxxxxxxxxxx",
"Discipline": "xxxxxxxxxxxxxxxx",
"Source": "xxxxxxxxxxxxxxxx",
"Email": "xxxxxxxxxxxxxxxx",
"PhoneNumber": "xxxxxxxxxxxxxxxx",
"URL": "xxxxxxxxxxxxxxxx"
}
]
}
Step 4:
Create an Array to store your value
var TableData:Array<String>=Array<String>()
On ViewDidLoad() method call your service
url_json_data("http://xxxxxx/xxxx/xxxx/xxxx/xxxxxx/xx")
On numberOfSectionsInTableView() Method Return "1"
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
On tableView() Method
return your array value
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return TableData.count
}
On tableView() for cell function do the fallowing
the "cell" is the name what you have assigned in the step 2
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text=TableData[indexPath.row]
return cell
}
Method To Parsing the JSON
func url_json_data(url:String)
{
let httpMethod = "GET"
let timeout = 15
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
let json = NSString(data: data, encoding: NSASCIIStringEncoding)
self.json_data_extractor(json!)
}else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
)
}
Method to extract the JSON Data
func json_data_extractor(data:NSString)
{
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
if (parseError == nil)
{
if let countries_list = json as? NSDictionary
{
if let Data_obj_list = countries_list["Data"] as? NSArray
{
println(Data_obj_list.count)
for(var i=0; i < Data_obj_list.count; i++)
{
if let country_obj = Data_obj_list[i] as? NSDictionary
{
if let country_name = country_obj["AccountName"] as? String
{
if let country_code = country_obj["Discipline"] as? String
{
if let email_id=country_obj["Email"] as? String
{
TableData.append(country_name + " , " + country_code + " , " + email_id)
}
}
}
}
}
}
}
}
refresh_table();
}
Method to refresh the Table
func refresh_table()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
Thats All!
Enjoy The Code!
Have A Happy Day..,