ios


tableView is not updating until i tap another tab and get back - swift


I'm new in iOS , i'm populating tableView data dynamically from a web source by parsing JSON data . But the problem is when i visit that tab first time its showing nothing . After i visit another tab and get back , its showing the data properly on tableView .
Here is my code
import UIKit
class BranchViewController: UITableViewController , UISearchBarDelegate, UISearchDisplayDelegate {
var branches = [Branch]()
var filteredBranch = [Branch]()
var BranchArray = [BranchTable]()
var BranchLocationArray = [BranchLocation]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView!.delegate = self
self.tableView!.dataSource = self
let url = NSURL(string: "http://rana.ninja/branches.php")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var error: NSError?
let jsonData: NSData = data /* get your json data */
let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
if let name: AnyObject = json["name"] {
for var index = 0; index < name.count; ++index {
var Name : String = name[index] as NSString
self.branches.append(Branch(name: Name))
println(Name)
}
}
}
task.resume()
BranchArray =
[BranchTable(BranchTitle: ["FirstFirst","SecondFirst","ThirdFirst"]),
BranchTable(BranchTitle: ["FirstSecond","SecondSecond","ThirdSecond"]),
BranchTable(BranchTitle: ["FirstThird","SecondThird","ThirdThird"]),
BranchTable(BranchTitle: ["FirstFourth"])]
BranchLocationArray = [BranchLocation(BranchLocationValues: ["asdfasd","asdfasd","asdfas"]),
BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"]),
BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"]),
BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"])]
// Reload the table
self.tableView.reloadData()
}
You need to call tableView.reloadData after you have updated the data structures. This has to be done in the main thread, thus:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var error: NSError?
let jsonData: NSData = data /* get your json data */
let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
if let name: AnyObject = json["name"] {
for var index = 0; index < name.count; ++index {
var Name : String = name[index] as NSString
self.branches.append(Branch(name: Name))
println(Name)
}
}
// NOTE: Calling reloadData in the main thread
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
It seems, your data loading completes asynchronously, but you are reloading the table outside of the closure, so it might be executed before the load is completed. So, you can put the table reload inside the closure.
And also, the suggested queuing way is nice, you can have a read on GCD in apple doc:
dispatch_async(dispatch_get_main_queue()) {
// Assign Job To The Main Queue
}
dispatch_async
Submits a block for asynchronous execution on a dispatch queue and returns immediately. It has two params - queue; The queue on which to submit the block & block The job to submit.

Related Links

Installing third party Objective-C library within Swift 3 / Xcode 8 (SharkORM)
How to Adjust UITableView Height According to the Height Change of the UITableViewCell Inside
Unsafe bytes in Swift 3
Creating an AVPlayerLayer causes simulator to crash
how to replace space with dash in objective-c?
Firebase Realtime Database Get Value and Increment
The model configuration used to open the store is incompatible with the one that was used to create the store
In iOs AVPlayer, addPeriodicTimeObserverForInterval seems to be missing
GCSVideoView can't set view mode
Can't use AutoLayout Constraints on UNNotificationContentExtension
Customize NavigationBar in IOS Objective c Application
mkmapview pin navigation like google map app
is possible play sound to speaker and connect airplay mirring at the same time
Lock only one ViewController's orientation to landscape, and the remaining to portrait
html geolocation extremely low accuracy in iOS safari on subsequent visits
IPv6 compatibilty in iOS?

Categories

HOME
math
ssis
opencv
hadoop
gwt
xaml
copy
module
load
telerik
binary-search
windows-10-desktop
boxfuse
reload
aar
w2ui
helpers
flow
pywin32
stackexchange-api
drupal-commerce
google-finance
jmeter-plugins
sfsafariviewcontroller
beanstalkd
csom
confidence-interval
parallax
listbox
ucwa
asp.net-identity-2
pmd
kubernetes-go-client
pyparsing
subtotal
outlook-vba
perl-module
sinon
windows-scripting
plasticscm
essbase
qmake
spark-submit
sweet.js
httpexception
distributed-lock
freecodecamp
pseudo-element
okular
abbyy
sshd
ietf-netconf
cmsmadesimple
a-star
catalina
findall
tachyon
olingo
ckcontainer
sqlfiddle
kernighan-and-ritchie
isapi-rewrite
gcloud-java
pakyow
balana
flexigrid
membership
samsung-gear
quasar
spymemcached
rdotnet
wt
bonfire
access-log
easynetq
diagonal
iife
adserver
tortoisecvs
tab-delimited
tinkerpop-frames
cellular-automata
master-theorem
jquery-backstretch
dirpagination
modalpopupextender
blazeds
mips64
emacs-jedi
hudson-plugins
cakephp-2.1
cocosbuilder
guvnor
xml-dtd
boost-gil
jquery-pagination
eye-detection
syncml
arraycopy
xml-database
dynamic-websites
cracker
newsgroup
sqlprofileprovider
ants
docking

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App