【发布时间】:2014-06-01 08:27:21
【问题描述】:
我正在为 iOS 7.1 编写我的第一个应用程序 Objective-c。我可能根本不明白我为什么会出现这个问题。
应用程序非常简单:客户端使用 web api 与外部服务进行通信。要发送 http 请求,我使用 NSURLSession。 我有一个简单的架构。
THETALETestViewController - 这个视图控制器。此类使用 THETALEAPI.h THETALEAPI——是web api的实现。我已经在一个单独的类中突出显示,每个外部 API 方法都已在一个地方实现。下面是每个方法的查询形成。此类使用 THETALEHttpHandler.h。 THETALEHttpHandler - 这个类直接负责发送http-request和接收http-response。
这是来自 THETALEHttpHandler.m 的代码,用于发送 POST - 查询。
-(void) sendPostToURL:(NSURL *)url withParams: (NSString *) inParams competion:(void (^) (NSData *data)) completion
{
NSLog(@"sendPostToURL");
// _csrftoken a token in cookie
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"csrftoken" forKey:NSHTTPCookieName];
[cookieProperties setObject:_csrftoken forKey:NSHTTPCookieValue];
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[_httpCookieStorage setCookie:cookie];
[_sessionConfig setHTTPCookieStorage:_httpCookieStorage];
// tried and so
// // NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil //delegateQueue: [NSOperationQueue mainQueue]];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:_sessionConfig];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
// _csrftoken a token in the parameter
NSString *params = [@[inParams, _csrftoken] componentsJoinedByString:@""];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Got response %@ with error %@.\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
completion(data);
}];
[dataTask resume];
}
所以,块完成不是在主线程中运行的,并且是异步的,所以当一个请求被发送并且有一个接收和处理响应时——主线程继续运行。原则上,它是清晰和合乎逻辑的,但我想分别使用这种方法“登录”,通过单击“登录”我必须在成功请求和响应后去处理用户应该看到答案。 iOS 有什么能力实现这样的行为,让主线程等待异步块的完成并显示相应的信息?或者也许它不值得等待,它只是需要通知?
当然,除非不创建单独的类,并且在 viewController 中做所有事情,那么,假设会出现委托,但我想在其应用程序中做一些模块化。
也许我设计的系统有误,那么您可以解释或展示一个通常如何完成的示例吗?
我认为这个要求相当平庸,答案就在附近,请解释一下,提前谢谢!
【问题讨论】:
-
对不起。翻译了代码中的cmets。
标签: ios objective-c ios7.1 nsurlsession