The Dark Dev Team. Powered by Blogger.

Web Service Apps in iOS8 JSON with UITableView by Swift Language

Let's Swift with iOS8 iPhone Developer in XCode6 BETA with JSON Data and UITableView step-by-step to show, how to display JSON data on UITableView 







In the last JSON and UITableView tutorial "Web Service Apps in iOS7 JSON with UITableView in XCode5", you learned the basics of the Objective-C language about JSON and UITableView. In this second tutorial about Web Service again, but i used Swift language.

My JSON format is:

[
  • {
    • item"1",
    • day_thai"พุธ",
    • day_eng"Wednesday",
    • date"01/01/2557",
    • title"วันขึ้นปีใหม่",
    • normal_vacation"Yes",
    • bank_vacation"Yes",
    • message"normal_vacation = วันหยุดราชการ, bank_vacation = วันหยุดธนาคาร"
    },
  • {
    • item"2",
    • day_thai"ศุกร์",
    • day_eng"Friday",
    • date"14/02/2557",
    • title"วันมาฆบูชา",
    • normal_vacation"Yes",
    • bank_vacation"Yes",
    • message"normal_vacation = วันหยุดราชการ, bank_vacation = วันหยุดธนาคาร"
    },
  • {
    • item"21",
    • day_thai"พุธ",
    • day_eng"Wednesday",
    • date"31/12/2557",
    • title"วันสิ้นปี",
    • normal_vacation"Yes",
    • bank_vacation"Yes",
    • message"normal_vacation = วันหยุดราชการ, bank_vacation = วันหยุดธนาคาร"
    }
]

The URL: http://www.linezeed.com/calendar.php?api_key=p24567739e33xcbnfg0, it's about my vacation.

Start! 
First open Xcode6 BETA and create New Single View Application and choose you project name in Swift Language.


Goto MainStoryBoard from project solution tree on you left side and drag UITableView object, paste it on ViewController.


Press and hold the Control key on your keyboard, select the Table View and drag to the "File’s Owner". Release both buttons and a popup shows both "dataSource" and "delegate".


Insert one prototype cell on your UITableView, 

create an Identity "Cell".



Next, select "ViewController.swift" Import "Foundation"  and append "UITableViewDelegate" after "UIViewController".

Chang this code below:

import UIKit
class ViewController: UIViewController{
to

import UIKit
import Foundation

class ViewController: UIViewController, UITableViewDelegate {
Create IBOutlet of UITableView like this:

@IBOutlet
var tableData: UITableView
Open MainStoryBoard press and hold the Control key again, select the icon "File’s Owner" (yellow one) drag it to release the UITableView:


Back to ViewController.swift file append "NSURLConnectionDelegate" before "UITableViewDelegate" and define an instance variable for holding the table data.

    let thetitle: NSString = "title"
    let thedate: NSString = "date"
    let day_thai: NSString = "day_thai"
    let err: NSError?
    let dictionary:NSDictionary?
    let myObject: NSMutableArray = []
Chang this code below:

class ViewController: UIViewController,UITableViewDelegate {
    
    @IBOutlet
    
    var tableData: UITableView
to

class ViewController: UIViewController,NSURLConnectionDelegate, UITableViewDelegate {
    
    @IBOutlet
    
    var tableData: UITableView
    
    let thetitle: NSString = "title"
    let thedate: NSString = "date"
    let day_thai: NSString = "day_thai"
    let err: NSError?
    let dictionary:NSDictionary?
    let myObject: NSMutableArray = []
In the "viewDidLoad" method, add the following code to initialise the JSON data array.

class ViewController: UIViewController,NSURLConnectionDelegate, UITableViewDelegate {
    
    @IBOutlet
    
    var tableData: UITableView
    
  override func viewDidLoad() {
        super.viewDidLoad()
        var urlPath = "http://www.linezeed.com/calendar.php?api_key=p24567739e33xcbnfg0"
        var jsonURL: NSURL = NSURL(string: urlPath)
        var URLrequest: NSURLRequest = NSURLRequest(URL: jsonURL)
        var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
        
        var jsonSource: NSData =  NSURLConnection.sendSynchronousRequest
             (URLrequest, returningResponse: response, error:nil)
        
        let jsonObjects = NSJSONSerialization.JSONObjectWithData
            (jsonSource, options: NSJSONReadingOptions.MutableContainers, error: nil) 
            as NSMutableArray
        
        
        var dataDict: NSDictionary
        for dataDict : AnyObject in jsonObjects {
            var title_data: NSString = dataDict.objectForKey("title") as NSString
            var date_data: NSString = dataDict.objectForKey("date") as NSString
            println("วันหยุดคือ:"+title_data+" ตรงกับวันที่:"+date_data+"")
            
            let dictionary = [thetitle: title_data, thedate: date_data]
            myObject.addObject(dictionary)
            
 
        }
        println(myObject.count)
        self.tableData.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

Add two datasource function: "tableView:numberOfRowsInSection" and "tableView:cellForRowAtIndexPath".

Used to inform the table view how many rows are in the section.
So let’s add the below code


//Table
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        
        return myObject.count
    }
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell{
        
        let tableCell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
        
        var tmpDict: NSDictionary = myObject[indexPath.row] as NSDictionary
        let text: NSMutableString = tmpDict.objectForKeyedSubscript(thetitle) as NSMutableString
        let detail: NSMutableString = tmpDict.objectForKeyedSubscript(thedate) as NSMutableString
        tableCell.text=text
        tableCell.detailTextLabel.text = detail
        
        return tableCell
    }
Overall code in "ViewController.swift" look like this:

import UIKit
import Foundation
 
class ViewController: UIViewController,NSURLConnectionDelegate, UITableViewDelegate {
    
    @IBOutlet
    
    var tableData: UITableView
    
    let thetitle: NSString = "title"
    let thedate: NSString = "date"
    let day_thai: NSString = "day_thai"
    let err: NSError?
    let dictionary:NSDictionary?
    let myObject: NSMutableArray = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var urlPath = "http://www.linezeed.com/calendar.php?api_key=p24567739e33xcbnfg0"
        var jsonURL: NSURL = NSURL(string: urlPath)
        var URLrequest: NSURLRequest = NSURLRequest(URL: jsonURL)
        var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
        
        var jsonSource: NSData =  NSURLConnection.sendSynchronousRequest
             (URLrequest, returningResponse: response, error:nil)
        
        let jsonObjects = NSJSONSerialization.JSONObjectWithData
            (jsonSource, options: NSJSONReadingOptions.MutableContainers, error: nil) 
             as NSMutableArray
        
        
        var dataDict: NSDictionary
        for dataDict : AnyObject in jsonObjects {
            var title_data: NSString = dataDict.objectForKey("title") as NSString
            var date_data: NSString = dataDict.objectForKey("date") as NSString
            println("วันหยุดคือ:"+title_data+" ตรงกับวันที่:"+date_data+"")
            
            let dictionary = [thetitle: title_data, thedate: date_data]
            myObject.addObject(dictionary)
            
 
        }
        println(myObject.count)
        self.tableData.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }
    
    //Table
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        
        return myObject.count
    }
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> 
           UITableViewCell{
        
        let tableCell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, 
             reuseIdentifier: "Cell")
        
        var tmpDict: NSDictionary = myObject[indexPath.row] as NSDictionary
        let text: NSMutableString = tmpDict.objectForKeyedSubscript(thetitle) as NSMutableString
        let detail: NSMutableString = tmpDict.objectForKeyedSubscript(thedate) as NSMutableString
        tableCell.text=text
        tableCell.detailTextLabel.text = detail
        
        return tableCell
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 
 
}
Run your project and see the log Console it's will show.


The JSON data will import to UITableView in iOS8 and Swift Language will complete!




Here is the final Xcode project with all the code from this Swift tutorial.

Tutorial in Thai Language: iPhone Developer (daydev.com)

0 comments:

Post a Comment

About

Daydev Co., Ltd. Thailand Outsources Service and IT Solution.

About