Swift UITableView: Load data from JSON

In this tutorial I'll explain you how to fill an iOS UITableView component by loading the data directly from an URL using the JSON format. You'll see how to define a tableview controller in swift, how to load the data from URL and how to extract the data from the JSON format.

Define the project 

Let's create a new Swift iOS single view project.


In the Main.storyboard you can disable the use size classes option.


Now you can remove the View controller that is inside the storyboard as default, we don't need that!


Define the layout and the custom classes

In the Main.storyboard you've to add the UITableViewController element.


Now you've to set a custom class for the UITableViewController that allows you to manage the data that will be displayed.

Create a new iOS Cocoa Touch Class and set the subclass as UITableViewController and the name of the class as TableController and create it.

Swift: add custom class


 Now in the Main.storyboard select again your UITableViewController and in the identity inspector set the TableController class that you've prevously created. 

Swift: set custom class


In the Attribute inspector turn on the is initial view controller option.

Swift: is initial controller


Now you have to select the table view cell and under the attribute inspector set the identifier to cell.  

Swift: cell identifier


TableController custom class

Now you've to implement the table controller class. This class is the core of the table. Here you'll define the download function, the json extractor function and finally the cell definition.

 The first thing you've to do is to define the array that will be used to store and read the data. Let's define the TableData String array as:

var TableData:Array< String > = Array < String >()

The viewDidLoad() is the function that will be called as soon as the view has been loaded. Inside it you should call the get_data_from_url function. We will define this function later, but let's add the function call placeholder.

var TableData:Array< String > = Array < String >()
override func viewDidLoad() {

At this link I've prepared for you a json object. This is a simple list of countries and countries' codes. If you want use this easy tool to explore this structure in a readable format.

Set the number of sections to 1 and the number of rows to the array's size.

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

Configure now the cell to load the array string at the position defined by the indexPath object. The "cell" identifier is the same identifier name that you previously set for the cell element. The cellForRowAtIndexPath function is called for every cell that is visible on the screen at a particular moment. So, for example, if you have to load 200 cells on your table, this function is called only 10-15 times, that's because only the elements that have to be displayed are loaded. Every time you scroll your table, this function is called again for the items that have to be displayed.
In this case we'll use the textlabel that is defined in the default cell layout.

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

let's define now the get_data_from_url function by exploiting the iOS asynchronous call.

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()
                                  queue: queue,
                                  completionHandler: {(response: NSURLResponse!,
                                                                   data: NSData!,
                                                                   error: NSError!) in
             if data.length > 0 && error == nil{
             }else if data.length == 0 && error == nil{
                 println("Nothing was downloaded")
             } else if error != nil{
                 println("Error happened = \(error)")

When the get_data_from_url function has done the download of the json data, the extract_json function is called. Let's now implement it. This function will extract the json data and fill the TableData array. In a JSON format there are two different main types: the array and the objects. Arrays are identified by the [ ] brackets while the object are identified by the { } brackets. This two types in Swift are defined by NSArray and NSDictionary respectively. For every JSON object you've to define a safe variable (using let and the question mark) with the right type. The json used in this example has this structure:

       name (String)
       code (String)
       name (String)
       code (String)

 Let's now implement the extract_json function.

func extract_json(jsonData:NSData)
     var parseError: NSError?
     let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
     if (parseError == nil)
        if let countries_list = json as? NSArray
           for (var i = 0; i < countries_list.count ; i++ )
               if let country_obj = countries_list[i] as? NSDictionary
                   if let country_name = country_obj["country"] as? String
                       if let country_code = country_obj["code"] as? String
                             TableData.append(country_name + " [" + country_code + "]")



Finally we have the data into our TableData array, we only have to refresh the table in the main thread.

func do_table_refresh()
     dispatch_async(dispatch_get_main_queue(), {


You can download the code for this example here.
UPDATE: download the swift 3 code example from here

Swift: TableView tutorial


Leave a comment


- 30 April 2018 at 09:24
Hi, I need send mysql sql query for show in uitableview like below: select * from table1 Can I use NSURLSession and How?
- 07 June 2017 at 14:15
All books Learn IOS by Ray Wenderlich (RxSwift, Ios Animations, Advanced Apple Debugging, Game 2d, 3d TvOs ...)new version swift 3 PDF Full source code Hello Everyone Recently I bought a set of 12 books Learn IOS, tutorial by Ray Wenderlich , And now I want to transfer it to you for $ 60 payment via Paypal, All books are the latest version that supports swift 3 and have full source code. I will share it for you for $ 60 Includes pdf and full source code, you can download on Google Drive, when the book has a new version i will get it for you if you are interested, please contact me by Email: [email protected] or skype: tvtruong91. Thank you You can see the full description at http://www.prograbooks.com/2017/05/download-all-books-learn-ios-by-ray.html 1. RxSwift Reactive Programming with Swift First Edition Ray Wenderlich 2. Advanced Apple Debugging & Reverse Engineering 3. Swift Apprentice Second Edition Begin Programming with Swift 3 Ray Wenderlich 4. Ios Apprentice Fifth Edition Begin IOS development with Swift 3 Ray Wenderlich 5. Tvos Apprentice Second Edition Begin TvOs development with Swift 3 Ray Wenderlich 6. Ios 10 By Tutorials First Edition Learning the new IOS 10 APIs with Swift 3 Ray Wenderlich 7. WatchOs By Tutorials Second Edition Making Apple Watch apps with watchOS 3 & Swift 3 Ray Wenderlich 8. Core Data By Tutorials Third Edition IOS 10 and Swift 3 edittion Ray Wenderlich 9. Ios Animations By Tutorials Third Edition IOS 10 and Swift 3 edition Ray Wenderlich 10. 2D Apple Games By Tutorials Begin 2D IOS & tvOS Game Development with Swift 3 Ray Wenderlich 11. 3D Apple Games By Tutorials Begin 3D IOS & tvOS Game Development with Swift 3 Ray Wenderlich 12. Unity Games By Tutorials Make 4 complete unity games from scratch Using C# Ray Wenderlich
- 19 May 2017 at 07:33
hi!! Thank you so much for this amazing tutorial.my question is what should I do if I have a design that prototype cell is having 2labels and image and all the data are coming from the API what steps I should follow..please help me by writing some code..thanks in advance
Andrea - 26 May 2017 at 17:53
Hi, thank you for your comment! You'll have to define your custom cell with all the labels and the image you need (https://www.kaleidosblog.com/uitableview-custom-cell-how-to-define-a-custom-cell-with-swift-in-ios). Then donwload your data, fill your custom data structure with the data, and refresh the table. When you fill your cell, you'll have to cast the UITableCellView into your custom cell, access to the variables linked using the assistand editor and fill everything! A bit summarized :) but hope it helps!
- 20 April 2017 at 13:18
Great Tutorial...
- 07 February 2017 at 14:04
Please post same project without using storyboard's drag and drop table view controller
- 07 January 2017 at 19:18
suppose we have json file Dic.JSON which is in the projects supporting files. Content of Json File is given Below var dictionary = [ { "name" : "Office Bearer", "members":[ { "name" : "Ashok Kr. Goyal", "designation" : "President" }, { "name" : "Rajesh Agarwal", "designation" : "Vice President" }, { "name" : "Girish Chand Goyal", "designation" : "Vice President" }, { "name" : "Rajeev Kr. Agarwal", "designation" : "Treasurer" } ] }, { "name" : "Members", "members":[ { "name" : "Abhishek Agarwal" }, { "name" : "Anil Agrawal Das"}, { "name" : "Anil Kumar Agarwal" }, { "name" : "Anil Mittal" }, { "name" : "Anoop Agarwal" }, { "name" : "Anuj Mangal" }, { "name" : "Anup Goyal" }, { "name" : "Dinesh Jain" }, { "name" : "Dr. SK Sahani" }, { "name" : "Gopal Khandelwal"}, { "name" : "Mahesh Chand Agarwal" }, { "name" : "Mukesh Garg" }, { "name" : "Murari Lal Goyal" }, { "name" : "Naresh Garg" }, { "name" : "Navneet Singhal" }, { "name" : "Raj Kumar Jain" }, { "name" : "Rajeev Bansal" }, { "name" : "Rakesh singhal" }, { "name" : "Ravi Agarwal"}, { "name" : "Sanjay Goyal" }, { "name" : "Shyam Sunder Agarwal" }, { "name" : "Surendra Kumar Jain" }, { "name" : "Sushil Bansal" }, { "name" : "Vishnu Kumar Garg" } ] }, { "name" : "Members", "members":[ { "name" : "Prahlad Kr. Agarwal" }, { "name" : "Puran Dawar"}, { "name" : "Shrikishan Goyal" } ] } ] This is the array of dictionaries I want to show the name s of the arrays as Section header and every section have no of members thats why i made array of members which i have to show in UITableViewCell. So please tell me how to do it.
- 29 December 2016 at 05:47
how to get any type of data instead of only string
Andrea - 04 January 2017 at 20:46
Hi, thank you for your comment. You just have to do the conditional casting with the type of variable you want. Otherwise if your json data contains only strings you can get the string and then cast the variable in the desired type.
- 10 October 2016 at 19:39
Hi! Thank you so much for your amazing tutorial. I have a question for you and I hope you can help me. For example, if I clic on Argentina cell I want to display some aditional information from Argentina, but in another tableview. I want to do this, with all the countries (working with Json file, as you did it in your awesome tutorial). Help me plesae, how can I do that?
Andrea - 19 October 2016 at 21:36
Hi, you can create another viewcontroller with another table. as soon as you press on the first main list of countries, you have to open this second activity by passing the id. At this point the new opened activity can display the extra information in your listview. Hope it helps.
- 10 October 2016 at 10:25
Hi Andrea , Thanks so much for your awesome tutorial. I tried implementing this tutorial with my project but my tableview shows up empty. Do you mind taking a look at it? Thanks!
Andrea - 19 October 2016 at 21:37
Hi, be free to send me your project to let me see. My email is [email protected]
- 30 September 2016 at 20:30
Working nice in swift 3, Thanks
- 29 September 2016 at 21:12
Hello, i was working with this project but in the the function get the json and in extract json i got a lot of errors, and i don't why. I'm working with swift 2 and i'm just trying to do exactly the same as in the tutorial. Thank you in advance
Andrea - 30 September 2016 at 20:44
Hi, are you using swift 2.2? Ca you plese send me your project to let me see and help?
- 28 September 2016 at 02:24
Hi! i found this tutorial very interisting, without doubt you are an amazing developer. I would like to ask you for some help, i'm creating an app that is suppose to take text information an images and place it an uitableview. But i have doubts on how to do it. Thanks in advance
Andrea - 28 September 2016 at 13:58
Hi, thank you for your comment, you have to define your data structure with the text information, image link and evetually the id for get some extra details after the user touch a row. Then during the cell population, you have to make the asynchronous request (better if you define a function that as an input will have the image link to download and the image view of the cell) to download your image and then display it inside your row. Hope it helps!
- 25 September 2016 at 08:02
Hi Andrea, These tutorials are exactly what I've been looking for, especially your update to Swift 3. Your code is so easy to read and your JSON is formatted exactly like the JSON I'm working with. I'm now going to try to move the data into the model, which will be a struct. I've also found your URLSession post/get version and want to use that to post data back to my server for dumping into MySQL. How would I go about putting the data together to send to the server for posting as JSON, for example using your country object in the JSON example. Thanks in advance.
Andrea - 25 September 2016 at 10:43
Hi, thank you for your comment. I have a tutorial about json parsing. Have a look at this tutorial! https://www.kaleidosblog.com/how-to-parse-and-extract-json-data-in-swift Hope it helps! :-)
Suzi - 25 September 2016 at 12:20
Thank you Andrea, I'll have a look.
- 09 September 2016 at 11:17
error in self.tableView.reload() statement. error is ambiguous reference to member tableview
Andrea - 09 September 2016 at 19:56
Hi, be sure to link the tableview using the assistant editor inside your uiviewcontroller class to the variable tableView!
- 27 August 2016 at 13:32
Andrea - 01 September 2016 at 08:50
Hi, what do you mean for nothing? Can you explain me the problem in order to let me help you?
- 24 August 2016 at 10:08
I tried to integrate your great tutorial into my own JSON on my server. I was able to build it without errors but the simulator shows a blank table. https://github.com/zeta1178/Test.git Could you provide some assistance?Thanks
Michael Cruz - 24 August 2016 at 19:10
I was able to figure out my problem was with the structure of the JSON file. Now I have another question. Can you help me add hyperlinks (pulled from the JSON) to the cell rows? Basically clicking on the table rows to link to a web page in safari. Thanks
Andrea - 01 September 2016 at 08:54
Hi, thank you for your comment. You can store the hyperlink in the swift array, then with the didselectrowatindexpath swift method you can manage the cell row click events. Hope it helps!
- 06 July 2016 at 12:22
Hey Andrea, thanks for this useful tutorial. I have tried with the codes for Swift 2, everything is OK but when I run I get "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)" in the AppDelegate and EXC_BAD_INSTRUCTION (code EXC_I386_INVOP, subcode = 0x0) can you please help me.
Andrea - 12 July 2016 at 13:37
Hi, thank you for your comment. Can you please send me your project to let me try it?
- 29 June 2016 at 13:08
Many thanks Andrea for your very clear tutorials and downloads. Helped me immensely!
Andrea - 01 September 2016 at 08:57
Thank you for your comment! You're welcome! :)
- 04 May 2016 at 15:43
hi,i am new to swift, i am getting error in this line, NSURLConnection.sendAsynchronousRequest( urlRequest, queue: queue, completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in Cannot convert value of type '(NSURLResponse!, NSData!, NSError!) -> Void' to expected argument type '(NSURLResponse?, NSData?, NSError?) -> Void' i don't knew how solve this, can you help me.
Andrea - 10 May 2016 at 12:45
Hi, can you please send me your project to let me help you? Send it here: [email protected]
- 05 April 2016 at 18:23
This is one of the only tutorials I have seen that actually tackles the problem head on and deals with the array and properly casts it do objects. I've been struggling on and off with other websites, particularly when their methods have been outdated and difficult to follow. I now have a working bit of my app. Thanks!
- 18 March 2016 at 14:52
Hi there, Im getting an error on line "tableview.dataSource = self" in viewDidLoad(), ViewController.swift ERROR: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)" Any idea why this is happening?
Andrea - 18 March 2016 at 18:55
Hi, thank you for your comment. It is better if I can see your project, but, be sure that with the assistant editor you've linked your UITableView to the tableview variable. Hope it helps
- 06 February 2016 at 09:35
Unable to download the file
Andrea - 07 February 2016 at 10:04
Hi, thank you for your comment. Which project aren't you able to download? The one for swift 1 or 2?
k - 09 February 2016 at 22:06
Same. The download link service you use (linkshrink) is super malware-y. It won't let me through to the files at all but gives me fake virus warnings (with 349085 popups and even audio, wth). Sucks. :( Why not just put the code on e.g. GitHub (Gist?).
k - 10 February 2016 at 12:23
See also: https://github.com/adsbypasser/adsbypasser/issues/826
Andrea - 10 February 2016 at 19:03
Hi, thank you for your feedback and note. I didn't know that..I will replace all the links with the original one. Thank you again
- 01 February 2016 at 14:39
Doesn't work in XCode 7
Andrea - 01 February 2016 at 20:56
Hi, thank you for your comment, the tutorial was written using the previous version of swift, however you can find the version for xcode 2 at the bottom of the article. Hope it helps!
- 05 January 2016 at 09:19
Thank You for great tutorial you help me more please i made a button and i want when i click the button data reload again like this ////// @IBAction func refreshAction(sender: AnyObject) { get_data_from_url(json_data_url) } ////// when i do that the data not change please help thank you
Andrea - 05 January 2016 at 09:42
Hi, thank your for your comment. First be sure that the action of your button is called, just use a print to be sure of that, then be sure to empty your array before the data extraction process, otherwise the data will be added and you'll have a double array, and check if the extracted array is the new one. Check this, if you have still problem send me the code so I can help. my email is [email protected]
Essa - 06 January 2016 at 08:29
Thank You Dear Andrea For helping me but I can't solve my problem yet I sent The project with email and thank you again for helping
- 26 December 2015 at 09:43
Hello , do you have any tutorial on how to save this data to your phone so later on we can view this data when we do not have internet connection.
Andrea - 26 December 2015 at 17:34
Hi, you can use core data to create an internal database, store the data, and retrieve them offline. You can find a tutorial here https://www.kaleidosblog.com/swift-core-data-how-to-store-objects about storing and reading data in core data. However, if you want, I can write a more detailed tutorial about storing data like this.
- 09 December 2015 at 13:43
I am trying to do something similar. I call a function to download my data async-ly in my viewDidLoad() and then call reload data once data is downloaded. But as the data download happens async-ly, even before the data download is complete, my numberOfRows gets called and crashes as I don't have any data in my array. Can you please suggest what am I doing wrong ? How can I ask my tableview datasource methods to wait till I get the data downloaded ? Please let me know if you need more inputs on my comment. Thanks in advance.
Andrea - 09 December 2015 at 21:59
Hi, I should see the code for better understanding. It could be an array that is initialized as nil and is filled only as soon as the data are arrived, but the number of rows is called before the data. Try this, perhaps some variables have to be checked before. Hope it helps, let me know!
- 07 December 2015 at 18:36
Hi, This has been an extremely helpful tutorial, thanks. I am trying to parse a file that is formatted like this but I can't work out how to get the objects into a swift array. heres the json.. any help is appreciated. { "LRKSFOweekdayDep": [{ "dep": ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"] }] "LRKSFOweekendDep": [{ "dep": ["9:30", "11:40", "13:40", "16:45"] }] }
Andrea - 07 December 2015 at 20:46
Hi, thank you for your comment. Your structure has an Object (LRKSFOweekdayDep) - Array - Object[dep] - Array. Firstly decode the object as NSDictionary (object) by writing if let dep_obj = ..json.. as? NSDictionary, then the array: if let array_dep = dep_obj["LRKSFOweekdayDep"] as? NSArray ; then if let dep = array_dep[0] as? NSDictionary and finally if let dep_values = dep["dep"] as? NSArray ..and here your can perform the for on dep_values :-). Hope it helps!
matt - 08 December 2015 at 17:05
Thanks.. I kind of got it working. Could I email you a playground file and ask you some advice on it?
Andrea - 08 December 2015 at 21:21
Sure, be free to send to [email protected]
- 22 November 2015 at 23:55
Hi, thanks so much for the tutorial. The original is exactly the kind of thing that I'm trying to do but the updated version of the code includes the images which is throwing me all off. I was wondering if you had an example that was like the original in Swift 2?
Nicole - 23 November 2015 at 00:11
Nevermind, I've got it figured out!
- 12 November 2015 at 17:13
Great tutorial, thanks. I've managed to amend the swift 2 code to connect to a php script and fill the datastruct dictionary with data, then display it all in labels within each table view cell. However some of the data are integers and dates, and I want to be able to manipulate them based on criteria but don't know how to successfully convert the string data to a date or where to put this manipulation. Should the manipulation go in the function cellForRowAtIndexPath? Thanks, Chris
Andrea - 12 November 2015 at 19:00
Hi, thank you for your comment. It depends from the data that is generated by your php script. Assuming that all the data, numbers and dates included, are sent as a String, you can define an array of different objects, with string, integer, dates..During the json extracting phase, you can convert the data in the format you want..for example int(string) for casting the string inside an int. At this point you have the array with the right data type, you can do the manipulation right at this step. Then inside the cellforrow turn back to string for displaying inside the uilabels, and you are done. Hope it helps!
Fergus Lo - 16 November 2015 at 17:21
Hi, Andrea love your tutorial, nice and easy to follow, but im very new to coding, i couldnt get following working: func get_data_from_url(........ CompleteionHandler:{...... and func extract_json(data:NSString) got an error on &parseError hi Chris, it is possible to share the amended code? Many thanks
Fergus - 17 November 2015 at 05:36
i amended it with the swift 2 example code, thanks, also added NSAppTransportSecurity NSAllowsArbitraryLoads on the info.plist
Fergus Lo - 17 November 2015 at 05:41
but i am wondering the Timeout code for swift 2, where can i add it?
Andrea - 17 November 2015 at 08:30
You can add the timeout code right in the NSMutableURLRequest definition (it's variable called request in the example). You can define the cache behaviour, the method for the request, and also the timeout. Just write something like: request.timeoutInterval = 10 ..Hope it helps!
- 31 October 2015 at 04:10
Hi Andrea Great tutorial - thanks. One problem I hope you can help with. The line 'let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)' generates an error 'extra argument 'error' in call' If I remove error I get the error 'Call can throw..... and the error is not handled' I am using swift 2.0 IOS 9 Any ideas? Cheers
Andrea - 31 October 2015 at 20:27
Hi Richard, thank you for your comment. Try the example-project for swift 2 ios 9 from here. https://www.kaleidosblog.com/tutorial/uitableview_load_data_from_json_swift_2.zip some things have been changed. Hope it helps!
- 04 October 2015 at 02:09
Andrea how does the json link function? is it just the json code or is it a php that downloads the json code
Andrea - 04 October 2015 at 08:48
Hi Danny, there is a php file that downloads the json code that is in another directory.
- 02 October 2015 at 07:00
Hi Andrea, can you mail me the code of the json array? or tell where can i find it, Thank you, this tutorial it really good, i really like your posts
Andrea - 02 October 2015 at 09:13
Hi Alex, you can find the json array at this link https://www.kaleidosblog.com/tutorial/tutorial.json
veca - 18 October 2015 at 19:42
link not working
- 28 September 2015 at 14:18
Hello Thanks a lot for the tutorial When i run my app i get a blank table, i am using xcode 7 and i used your swift 2 code, as a test i made an array of fruits and they were displayed in the table, but when i am using the TableData array nothing is displayed. Can you help me fix this please. Thanks in advance.
Ali - 28 September 2015 at 14:32
I got this error message TableView[3483:576754] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
Andrea - 28 September 2015 at 14:51
Hi thank you for your comment. In Swift 2 with the new iOS 9 sdk the http traffic is blocked. You have to allow this kind of traffic by editing the info.plist file, have a look here for allowing the http traffic from a single domain https://www.kaleidosblog.com/nsurlsession-in-swift-get-and-post-data . Otherwise if you want to allow the http traffic from any domain, just write: < key > NSAllowsArbitraryLoads < / key > < / true > inside the NSAppTransportSecurity key. Hope it helps!
Ali - 28 September 2015 at 15:22
Hi Thank you very very much for your fast respond, it is working fine.
Baltieri - 14 October 2015 at 10:12
Hi, thank you for the tutorial, im using xcode 7 and I got this error: let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) Extra argument 'error' in call Can you help me fix this, Thanks
Baltieri - 14 October 2015 at 16:08
Hello Ali, how do you change the code to run on swift 2, I got this error after update to xcode 7: Extra argument 'error' in call in this line: let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) Thanks
Andrea - 03 November 2015 at 21:44
Hi, here you can find the example for swift 2 ios 9. Hope it helps! https://www.kaleidosblog.com/tutorial/uitableview_load_data_from_json_swift_2.zip
- 09 September 2015 at 14:25
Hi , Could anybody please help me regarding this. array contains array of objects in json format. Wanted to show in the table view where every row shows 4 string in 4 labels. I am able to display 1 label in each row. Thanks in advance.
Andrea - 09 September 2015 at 14:53
Hi, thank you for your comment. The first thing is to extract the whole array/object data inside an array/object swift structure. At this point in order to properly display the data you need to define a custom cell with all the uilabel you need (and of course the position you want). To define a custom cell have a look at this tutorial https://www.kaleidosblog.com/uitableview-custom-cell-how-to-define-a-custom-cell-with-swift-in-ios (paragraph Custom UITableViewCell: Layout Definition). Let me know if it can help.
- 29 August 2015 at 00:10
Hello. Nice tutorial, just a question, how can i change the strings and apply them to Title and subtitle? not all in the same row, thank you!
Andrea - 30 August 2015 at 10:01
Hi, thank you for your comment. You have to define in swift a multidimensional array with all the fields you need, append the needed data in the extract_json function. You have then to create a custom cell with all the UIlabel you need (https://www.kaleidosblog.com/uitableview-custom-cell-how-to-define-a-custom-cell-with-swift-in-ios). Then in the cellForRowAtIndexPath function you'll able to read your fields and assign them. If you need a more concrete example just let me know.
- 24 August 2015 at 13:24
Hello. Great tutorial. How i put an imagem from URL using this code?
Andrea - 24 August 2015 at 15:48
Hi, thank you for your comment. You have to add in your json code the image url/name, then download it (when displayed) in an asynchronous way. You can find an example here: https://www.kaleidosblog.com/swift-cache-how-to-download-and-cache-data-in-ios
- 12 August 2015 at 02:32
Hello Andrea ! thanks for your response, i'm searching an example to retrieve data from my database mysql and loading in a tableView with a UISearchBar for the moment using the code above i can filtering my data ! but like to use the : /* In the same Cell */ TextLabel = to show the title detailTextLabel = to show the description imageView = to show a thumbnail below my complete code : import UIKit class SecondViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var activityIndicatorText: UILabel! @IBOutlet weak var activityIndicatorView: UIView! var tableData:Array< String > = Array < String >() let LocalData:NSUserDefaults = NSUserDefaults.standardUserDefaults() //SEARCH/////////////////// var filteredTableData = [String]() var resultSearchController = UISearchController() //SEARCH/////////////////// override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. get_data_from_url("http://www.rtzauto.ch/application/ACCESSOIRES_JSON2.php") self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); //SEARCH///////////////// self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() self.tableView.tableHeaderView = controller.searchBar return controller })() self.tableView.reloadData() //SEARCH////////////////// } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var nav = self.navigationController?.navigationBar nav?.barStyle = UIBarStyle.Black nav?.tintColor = UIColor.whiteColor() nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] } 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: NSUTF8StringEncoding) 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(NSUTF8StringEncoding)! let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) if (parseError == nil) { if let vehic_list = json as? NSArray { for (var i = 0; i < vehic_list.count ; i++ ) { if let vehic_obj = vehic_list[i] as? NSDictionary { if let vehic_marque = vehic_obj["techniques_marque"] as? String { if let vehic_modele = vehic_obj["techniques_count"] as? String { tableData.append(vehic_marque) // I can only retrieve one object at a time how to retrieve many object in the same row using tableData.append ??? } } } } } } do_table_refresh() } func do_table_refresh() { dispatch_async(dispatch_get_main_queue(), { self.activityIndicator.hidesWhenStopped = true self.activityIndicatorView.hidden = true self.activityIndicatorText.hidden = true self.tableView.reloadData() return }) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.resultSearchController.active) { return filteredTableData.count } else { return tableData.count } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell") if (self.resultSearchController.active) { cell.textLabel?.text = filteredTableData[indexPath.row] // Disclosure show cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } else { cell.textLabel?.text = tableData[indexPath.row] // Disclosure show cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } } func updateSearchResultsForSearchController(searchController: UISearchController) { self.filteredTableData.removeAll(keepCapacity: false) let searchPredicate = NSPredicate(format: "self contains[c] %@", searchController.searchBar.text) let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate) self.filteredTableData = array as! [String] self.tableView.reloadData() } // Line separator appears under image into tableView override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.separatorInset = UIEdgeInsetsZero } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //let modelsArray : NSMutableDictionary = self.tableData[indexPath.row] as! NSMutableDictionary //var modelSelected = modelsArray["data"]!["techniques_marque"] as? String //LocalData.setObject(modelSelected, forKey: "ModelsVehic") self.performSegueWithIdentifier("VehicToModelsSegue", sender: self) } } when using the example above this working fine but i can only retrieve one object at "tableData.append(vehic_marque)" loading it in the tableView at cell.textLabel?.text = tableData[indexPath.row] cell.detailTextLabel?.text = ??? <--- vehic_model cell.ImageView?.image = UIImage(named: myimge) ???? <-- vehic_logo many Thanks Robin
Andrea - 12 August 2015 at 14:58
Hi Robin, can you please send me an email with this code? I can't read it, the comments are without breakspaces. You can send it to [email protected]
- 07 August 2015 at 19:27
Hello Thanks for your code, do you know how to field my tableView ? override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell") cell.textLabel?.text = tableData[indexPath.row] // I can only retrieved data for textLabel works fine ! cell.imageView?.image = UIImage(named: ?????) // ???? I dont know how to field this cell.detailTextLabel?.text = ???? // ???? I dont know how to field this } my json return data like this: {"title": "My Title", "Description": "My Description", "Image": "My image"} Thanks for your answer. Robin
Andrea - 08 August 2015 at 15:58
Hi Robin, you have to define an array with a custom struct with the image link, description, title..every field you need. for the image you can set in your json data the link of the image then read it as a string and download it in an asynchronous way. If you need an example, tell me.
- 20 July 2015 at 21:46
Works fine, thanks!
mahbod - 06 November 2016 at 12:13
Hi Thank you for your tutorial. I want show news that came from my database website into application. I create table in my mysql database and I create news page with Image and detail and now I want connect application to news page of my website and every time I create new News when user reload the application can see the news page. could you please help me ? thank you so much
Kunal - 14 April 2017 at 10:29
Hello, i have one question, in my tableviewcell i take uitextfield then how to store it in array that present in my view controller button action