Mirko Brombin
Mirko Brombin

Reputation: 1012

Group JSON data in Tableview with Swift

I'm creating an app for iOS that get data from my server with json and store it on a tableview; with this no problems, my data are simple notes, some notes are linked together forming projects (simple dependency_id on my database sql), my question is: How can i group my notes by project, like a contact list? (ex. http://img.wonderhowto.com/img/13/66/63535060544981/0/siri-exploit-you-could-bypass-iphones-lock-screen-call-message-any-contact-ios-7-1-1.w654.jpg)

This is the source that populate the table with all notes:

//
//  TableController.swift
//  uitableview_load_data_from_json

import UIKit

class TableController: UITableViewController {

var TableData:Array< String > = Array < String >()
var userid = NSUserDefaults.standardUserDefaults().stringForKey("userid")!

override func viewDidLoad() {
    super.viewDidLoad()
    get_data_from_url("http:/localhost/index.php/iOS_getNomenTasks?n=" + userid)
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return TableData.count
}

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
}


func get_data_from_url(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.extract_json(json!)
            }else if data.length == 0 && error == nil{
                println("Nothing was downloaded")
            } else if error != nil{
                println("Error happened = \(error)")
            }
        }
    )
}

func extract_json(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 task_list = json as? NSArray
        {
            for (var i = 0; i < task_list.count ; i++ )
            {
                if let tasj_obj = task_list[i] as? NSDictionary
                {
                    if let task_id = tasj_obj["id"] as? String
                    {
                        if let task_name = tasj_obj["tk_title"] as? String
                        {
                            if let task_type = tasj_obj["tk_type"] as? String
                            {
                                TableData.append(task_name)
                            }
                        }
                    }
                }
            }
        }
    }
    do_table_refresh();
}


func do_table_refresh()
{
    dispatch_async(dispatch_get_main_queue(), {
        self.tableView.reloadData()
        return
    })
}
}

ok.. task_id is the note id, task_name is the note name, task_type is the value that identify if note is a project or not, if task_type is 0, the note is a simple note, if task_type is 1 the note is a project.

Upvotes: 0

Views: 961

Answers (1)

Betcha
Betcha

Reputation: 175

If you create an UITableViewController, you have the function :

override func numberOfSectionsInTableView(tableView: UITableView) -> Int

With it, you have 3 sections who contains 2 lines :

var tab: [String] = ["section 1", "section 2", "section 3"]

var tabData: [AnyObject] = [["item1", "item2"],["item1", "item2"],["item1", "item2"]]

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     return tab.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return self.dataTab[section].count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     var cell: UITableViewCell = UITableViewCell()
     return cell
}

Upvotes: 1

Related Questions