gpt4 book ai didi

ios - 使用 NSURLSession 设计简单的 ios 应用程序

转载 作者:行者123 更新时间:2023-11-29 03:02:50 25 4
gpt4 key购买 nike

我正在为 iOS 7.1 编写我的第一个应用程序 objective-c。我可能从根本上不明白为什么我会出现这个问题。

应用程序非常简单:客户端使用 web api 与外部服务通信。要发送 http 请求,我使用 NSURLSession。我有一个简单的架构。

THETALETestViewController - 这个 View Controller 。此类使用 THETALEAPI.hTHETALEAPI - 是 web api 的实现。我在一个单独的类中突出显示,每个外部 API 方法都在一个地方实现。下面是每个方法的查询形成。此类使用 THETALEHttpHandler.h。THETALEHttpHandler - 该类直接负责发送 http 请求和接收 http 响应。

这是来自 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];

}

因此, block 完成不是在主线程中运行,并且是异步运行,因此当发送请求并且有接收和处理响应时 - 主线程运行。原则上,这是清晰和合乎逻辑的,但我想分别使用这种方法“登录”,通过单击“登录”,我必须在成功请求和响应后进行处理,用户应该看到答案。 iOS 有什么能力实现这样的行为来让主线程等待异步 block 的完成并显示相应的信息?或者也许它不值得等待,它只是需要以某种方式通知?

当然,除非不创建单独的类,并在 viewController 中执行所有操作,然后假设会出现委托(delegate),但我想在其应用程序中进行一些模块化。

也许我设计的系统有误,那么您可以解释一下或举例说明它通常是如何完成的?

我认为这个要求相当平庸,答案就在附近,请解释,提前致谢!

最佳答案

您可以使用AFNetworking用于 API 调用。 Tutorial详细解释如何正确使用它。您也可以使用 NSNotificationCenter当调用成功/失败时通知 View Controller

关于ios - 使用 NSURLSession 设计简单的 ios 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23126830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com