Currently I am calling an API in viewcontroller
itself but this is not good programming practice as per MVC.
Here is my code:
-(void)fetchData{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[request setHTTPMethod:@"GET"];
[request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"text/plain" forHTTPHeaderField:@"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
if (responseData != nil) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"requestReply: %@", jsonDict);
self.content = jsonDict[@"rows"];
self.navigationTitle = jsonDict[@"title"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
NSLog(@"result %@", self.content);
}
}] resume];
}
Can you please suggest how should I arrange code/file to follow MVC pattern?
If I create separate model class how should I manage existing code and how I transfer response to viewcontroller
?
Swift 3 Try this:
ObjectiveC
WebRequester.h
WebRequester.m
call as follow