Matthew Evans Matthew Evans - 1 year ago 83
iOS Question

How do I load view THEN load data in Xcode?

thanks in advance.

I am wondering if you could help me with loading data after the view has loaded. I am using a url to load data into my label, though, overtime you open the page it needs to download the information before displaying the view. Is there a way to display the view as the information is being downloaded, and the information appear when ready?

The code I am currently using is:

- (void)viewDidLoad {

NSURL *urlTitle = [NSURL URLWithString:@" URL GOES HERE "];
NSString *TitleLabel = [NSString stringWithContentsOfURL:urlTitle encoding:NSStringEncodingConversionAllowLossy error:nil];
TermTitleLabel.text = TitleLabel;

[super viewDidLoad];
// Do any additional setup after loading the view.


Answer Source

You can display the view in the viewDidLoad method along with a loading animation or "Loading..." message. This would ensure that the label and the loading message / animation appear together.

Use NSURLSession's dataTaskWithRequest to download your data from the URL. You can do this in the viewWillAppear or viewDidAppear methods. viewDidAppear would be a better choice if the quantity of data to be downloaded is huge.

The dataTaskWithRequest's completion handler can be used to load the data into your label and to remove the loading message / animation.

You can check this blog post on where you can layout / load views:

Check this Stack Overflow post to find out the difference between viewDidLoad, viewWillAppear and viewDidAppear: What is the difference between -viewWillAppear: and -viewDidAppear:?