I'm starting from scratch learning iOS programming.
I want my app to pull XML from a website. I'm thinking that to conform with the MVC pattern I should have a model class that simply provides a method to accomplish that (maybe have it parse the XML too and return an array).
Trouble is that all the tutorials I have found teach the NSURLSession in the context of the view and controller - so edit the appdelegate, or create a view controller, etc.
I got the following method from Apples documentation and I currently have it running as an IBAction when a button is pressed (so I can run it and test it easily). I'd like to get it working then put it in it's own class:
__block NSMutableData *webData;
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *delegateFreeSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
[[delegateFreeSession dataTaskWithURL: [NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(@"Got response %@ with error %@.\n", response, error);
NSLog(@"DATA:\n%@\nEND DATA\n", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]);
webData = [[NSMutableData alloc] initWithData:data];
}
]resume];
My immediate question is:
Can someone explain how the completion handler is working and how to get data
out of there? It's working, data is grabbing the xml from the website and logging it on the console, but copying it to webData
doesn't work, it compiles but doesn't copy. (I'm still figuring out why the __block
declaration allows webData
to sneak in there in the first place!)
My bigger question would be if everyone thinks the idea of a separate model class for this process is a good idea. Is there a better way of designing this?
Thank you!