我应该如何创build模型类来调用API(使用MVC模式)?
目前我在viewcontroller
本身调用一个API,但这不是每个MVC的良好的编程实践。
这是我的代码:
-(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]; }
你能build议我应该如何安排代码/文件遵循MVC模式?
如果我创build单独的模型类,我应该如何pipe理现有的代码,以及如何将响应传递给viewcontroller
?
Swift 3试试这个:
class WebRequester: NSObject { static let shared = WebRequester() func request(vc:UIViewController, url: String, parameter:String?, callback:@escaping (_ result:NSDictionary?, _ error:NSError?) -> Void) { let requestURL = url print("..............................") print("URL: ",requestURL) print("Parameter: ",parameter ?? "nil") print("..............................") var request = URLRequest(url: URL(string:requestURL)!) request.httpMethod = "POST" if parameter != nil { request.httpBody = parameter!.data(using: .utf8) } let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: {data, response, error in UIApplication.shared.isNetworkActivityIndicatorVisible = false DispatchQueue.main.async { if error == nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) print(json) let dic = json as? NSDictionary if dic != nil { callback(json as? NSDictionary, nil) } else { vc.alert(title: "Oops..", message: "Something went wrong please try again later") } } catch { print(error.localizedDescription) callback(nil,error as NSError?) } } else { print(error?.localizedDescription ?? "") callback(nil, error as NSError?) } } }) task.resume() UIApplication.shared.isNetworkActivityIndicatorVisible = true } }
的ObjectiveC
WebRequester.h
#import <Foundation/Foundation.h> @interface WebRequester : NSObject +(id)shared; -(void)request1:(NSString *)url parameter:(NSString *)params callback:(void(^)(NSDictionary *result, NSError *error))callback; @end
WebRequester.m
#import "WebRequester.h" @implementation WebRequester +(id)shared { static WebRequesterObjC *sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager; } -(void)request1:(NSString *)url parameter:(NSString *)params callback:(void(^)(NSDictionary *result, NSError *error))callback { NSString *requestUrl = url; NSLog(@"===================="); NSLog(@"%@",requestUrl); NSLog(@"%@",params); NSLog(@"===================="); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:requestUrl]]; request.HTTPMethod = @"POST"; if (params != nil) { request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; } NSURLSession* session = [[NSURLSession alloc] init]; NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error == nil) { if (data != nil) { NSError * err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err]; if (err == nil) { callback(dic,nil); } else { callback(nil,err); } } } else { callback(nil,error); } }]; [task resume]; } @end
打电话如下
[WebRequesterObjC.shared request1:<#url#> parameter:params callback:^(NSDictionary *result, NSError *error) { if (error == nil) { NSLog(@"%@",result) } }];