[英]Activity Indicator startAnimating before NSURL Call
我有一种方法可以通过NSURL访问我的网站。 这工作得很好,但是我希望有一个活动指示器在处理网络呼叫时显示。
我的问题是,直到NSURL调用完成后,活动指示器才会出现。 我尝试过包括使我的活动指示器显示在方法顶部的两段代码(请参见下文)。 我确定在更新UI时有一定的关系,但是我不知道如何处理。 我想要的只是让活动指示器开始动画制作,以及让loadImageView立即出现。 任何帮助都会很棒。 谢谢!
- (IBAction)buttonPress:(id)sender {
//ACTIVITY INDICATOR STARTS WITH THESE TWO LINES
loadingImageView.hidden = false;
[activityIndicator startAnimating];
NSString *c = [view.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *b = [[NSUserDefaults standardUserDefaults] stringForKey:@"b"];
NSString *a = [[NSUserDefaults standardUserDefaults] stringForKey:@"a"];
NSString *strURL = [NSString stringWithFormat:@"http://www.website.com/page.php?
a=%@&b=%@&c=%@",a, b, c];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL
encoding:NSUTF8StringEncoding];
NSLog (@"%@", strResult);
[[NSUserDefaults standardUserDefaults] setObject:@"true" forKey:@"newKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self dismissViewControllerAnimated:YES completion:nil];
}
您应该将网络代码放在后台队列中,否则UI会冻结,就像您现在正在经历的那样
你可以做类似的事情
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
[backgroundQueue addOperationWithBlock:^{
//Your network code
}];
+[NSData dataWithContentsOfURL:]
方法是同步的:这意味着它将阻塞直到数据传输完成。 您永远都不想在主线程上执行此操作,因为在数据传输期间UI会阻塞。
因此,您应该将数据传输移动到另一个线程,例如,通过将其包装在一个方法中,然后使用[self performSelectorInBackground:@selector(foo) withObject:nil]
或GCD来调用它:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Insert netword code here.
// Once done, resume on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
// Code to update the UI or something.
});
});
解决此问题的另一种方法是使用异步数据传输,例如使用NSURLConnection 。
您还可以使用Grand Central Dispatch(GCD)在后台按如下代码调用您的URL,例如以下代码:-
loadingImageView.hidden = false;
[activityIndicator startAnimating];
__Block NSString *c = [view.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
__Block NSString *b = [[NSUserDefaults standardUserDefaults] stringForKey:@"b"];
__Block NSString *a = [[NSUserDefaults standardUserDefaults] stringForKey:@"a"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *strURL = [NSString stringWithFormat:@"http://www.website.com/page.php?a=%@&b=%@&c=%@",a, b, c];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog (@"%@", strResult);
[[NSUserDefaults standardUserDefaults] setObject:@"true" forKey:@"newKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:YES completion:nil];
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.