- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 Objective C 和 iOS 开发总体来说是新手。我正在尝试创建一个应用程序,它会发出 http 请求并在标签上显示内容。
当我开始测试时,我注意到标签是空白的,尽管我的日志显示我已经恢复了数据。显然发生这种情况是因为标签文本更新时响应尚未准备好。
我在顶部放了一个循环来解决这个问题,但我几乎确信一定有更好的方法来处理这个问题。
ViewController.m
- (IBAction)buttonSearch:(id)sender {
HttpRequest *http = [[HttpRequest alloc] init];
[http sendRequestFromURL: @"https://en.wiktionary.org/wiki/incredible"];
//I put this here to give some time for the url session to comeback.
int count;
while (http.responseText ==nil) {
self.outputLabel.text = [NSString stringWithFormat: @"Getting data %i ", count];
}
self.outputLabel.text = http.responseText;
}
HttpRequest.h
#import <Foundation/Foundation.h>
@interface HttpRequest : NSObject
@property (strong, nonatomic) NSString *responseText;
- (void) sendRequestFromURL: (NSString *) url;
- (NSString *) getElementBetweenText: (NSString *) start andText: (NSString *) end;
@end
HttpRequest.m
@implementation HttpRequest
- (void) sendRequestFromURL: (NSString *) url {
NSURL *myURL = [NSURL URLWithString: url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: myURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest: request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
self.responseText = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
}];
[task resume];
}
非常感谢您的帮助:)
在阅读了很多这里非常有用的评论之后,我意识到我错过了全部要点。因此,从技术上讲,NSURLSessionDataTask 会将任务添加到队列中,该队列将异步进行调用,然后我必须为该调用提供一段代码,以便在任务生成的线程完成时执行。
Duncan 非常感谢您的回复和代码中的评论。这对我的理解有很大帮助。
所以我使用提供的信息重写了我的程序。请注意,它们有点冗长,但我希望现在能理解整个概念。 (我声明一个代码块而不是嵌套它们)
HttpRequest.m
- (void) sendRequestFromURL: (NSString *) url
completion:(void (^)(NSString *, NSError *))completionBlock {
NSURL *myURL = [NSURL URLWithString: url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: myURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest: request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Create a block to handle the background thread in the dispatch method.
void (^runAfterCompletion)(void) = ^void (void) {
if (error) {
completionBlock (nil, error);
} else {
NSString *dataText = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
completionBlock(dataText, error);
}
};
//Dispatch the queue
dispatch_async(dispatch_get_main_queue(), runAfterCompletion);
}];
[task resume];
}
ViewController.m
- (IBAction)buttonSearch:(id)sender {
NSString *const myURL = @"https://en.wiktionary.org/wiki/incredible";
HttpRequest *http = [[HttpRequest alloc] init];
[http sendRequestFromURL: myURL
completion: ^(NSString *str, NSError *error) {
if (error) {
self.outputText.text = [error localizedDescription];
} else {
self.outputText.text = str;
}
}];
}
请随时对我的新代码发表评论。风格、不正确的用法、不正确的流程;在这个学习阶段,反馈非常重要,这样我才能成为更好的开发人员:)
再次非常感谢您的回复。
最佳答案
你知道吗,使用 AFNetworking以挽救您的生命。
或者只是修改你的 HttpRequest 的 sendRequestFromURL:
- (void)sendRequestFromURL:(NSString *)url completion:(void(^)(NSString *str, NSError *error))completionBlock {
NSURL *myURL = [NSURL URLWithString: url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: myURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest: request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
completionBlock(nil, error);
} else {
completionBlock([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], error);
}
});
}];
[task resume];
}
并像这样调用
[http sendRequestFromURL:@"https://en.wiktionary.org/wiki/incredible" completion:^(NSString *str, NSError *error) {
if (!error) {
self.outputLabel.text = str;
}
}];
关于ios - 等待 NSURLSessionDataTask 回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628930/
我有一个使用 NSURLSessionDataTask 调用 API 的函数,您可以在此处查看它: - (void)getExplorerUrl:(void (^)(NSString *))measu
我正在尝试向服务器发出请求,该请求应该返回我可以在应用程序的其余部分中使用的数据。这是我的代码: func makeNewUser() -> NSDictionary { var full_u
我正在使用 AFNetworking 并且我正在覆盖 -dataTaskWithRequest:completionHandler: 以基本上 MITM 我的请求并在调用实际响应 block 之前进行
我使用 NSURLSessionDataTask 获取 JSON 提要,并填充位于共享存储(单例)内的 NSMutableArray。外部世界可以通过将其转换为 NSArray 的 getter 来访
我不知道如何同步 NSURLSessionDataTask。 如何在 syncInfo1Info2 中同步这两个 session : - (void) syncInfo1Info2 { //How
我想知道 NSURLSessionDataTask 在后台的行为。 NSURLSessionDataTask 是否会立即暂停(一旦应用程序进入后台)?还是 iOS 会给出一些时间(希望有 30 秒左右
我正在创建一个 NSMutableRequest: self.req = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequ
当我开始使用 NSURLSessionDataTask 下载文件时,有一段时间进度不工作。然后在完成下载后只显示全蓝色的进度条。 我的代码 - (void)URLSession:(NSURLSess
我对 Objective C 和 iOS 开发总体来说是新手。我正在尝试创建一个应用程序,它会发出 http 请求并在标签上显示内容。 当我开始测试时,我注意到标签是空白的,尽管我的日志显示我已经恢复
我正在学习有关访问 API 和解析结果的教程。我正在逐字逐句地学习教程,但由于“预期返回‘NSURLSessionDataTask’的函数中缺少返回值”,我无法运行该程序 所以我将返回语句更改为“re
我要使用 NSURLSessionDataTask 执行请求链。当第一个请求完成时,我需要使用第一个请求中的 responseData 来执行另一个多重请求。最后,我得到 NSArray 并提供给 T
我正在尝试从将同时运行的多个 NSURLSessionDataTasks 中聚合数据。 __block NSMutableDictionary *languageDetails = [NSMutabl
我刚刚用 Swift 开发了一个库,用于将数据发布到特定服务器。我使用 NSURLSession.sharedSession().dataTaskWithRequest(request) 打开连接。现
我有一个 iOS 应用程序,它使用 NSOperationQueue、NSOperations 和 AFNetworking 2.1.0 来触发对服务器的请求。 -[NSOperation main]
我知道我可以使用 dataTaskWithURL:completionHandler: 获取 completionHandler block 中的数据,但这会阻止触发委托(delegate)方法,我需
场景: 作为用户,我可以拍摄(无限量)存储在应用程序文档文件夹中的照片和视频。这些媒体文件中的每一个都会在 Sqlite 数据库中获得一条记录,其中包含附加信息(例如标题)。所有这些都可以完全离线完成
在使用 NSURLSessionDataTask 向服务器发送 JSON 请求时,我遇到了一个非常奇怪的问题。 第一个请求通过并且我收到正确的 JSON 响应,当我执行第二个请求时,我总是得到旧的响应
我想确定来自 NSURLSessionDataTask 的响应是来自缓存,还是来自服务器 我正在从 创建我的 NSURLSessionDataTask request.cachePolicy = NS
我有一个注册 View Controller ,它处理所有用户输入并调用传递给它的另一个类 (wsClass) 中的函数,该数据作为 NSDictionary。 调用 wsClass 中的函数并建立连
我从 Web 获取 JSON 数据,对其进行解析,然后使用它在 map 上显示图钉。 这里是方法一,没有问题: NSString *CLIENT_ID = @"SECRET_ID"; NSSt
我是一名优秀的程序员,十分优秀!