1

因此,我通常为 android 编写应用程序,并且只使用异步任务来调用在后台运行的方法,同时播放警报对话框,显示“正在加载”或类似的内容。在这个应用程序上,我试图翻译到 iOS,我解析来自不同网站的数据并显示几个网络图像,我希望在加载所有这些内容时播放我的警报对话框。我一直在寻找几个小时,并没有找到我正在寻找的解决方案。我希望有人能指出我的教程或正确方向的某个地方。

这是我的工作:

- (void) RSEpic{
NSURL * imageURL = [NSURL URLWithString:RSEimageURL];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
_RSEImage.image = image;
[self waterTemp];
}

- (void) waterTemp{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:@"http://waterdata.usgs.gov/usa/nwis/uv?02035000"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL       error:NULL];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:@"<table id=\"table_12_00010\"" intoString:NULL];
[scanner scanUpToString:@"&nbsp" intoString:&token];
NSArray *words = [token componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]];
double temp = [words[1] doubleValue];
_waterTempC.Text = [NSString stringWithFormat:@"%.2f°C",temp];
_waterTempF.Text = [NSString stringWithFormat:@"%.2f°F",temp*9/5+32];
[self waterDepth];
}

- (void) waterDepth{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:@"http://waterdata.usgs.gov/va/nwis/uv?02037500"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:@"<table id=\"table_07_00065\"" intoString:NULL];
[scanner scanUpToString:@"&nbsp" intoString:&token];
NSArray *words = [token componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]];
double temp = [words[1] doubleValue];
_waterLevel.Text = [NSString stringWithFormat:@"%.2fFT",temp];
if (temp >= 9.0) {
    _levelAlert.text = @"HIGH WATER PERMIT REQUIRED";
    }
else if (temp >= 5.0){
    _levelAlert.text = @"LIFE JACKET REQUIRED";
}
else {
    _levelAlert.text = @"";
}
[self tempChart];
}

- (void) tempChart{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:@"http://waterdata.usgs.gov/nwis/uv/?dd_cd=12_00010&format=img_default&site_no=02035000&set_arithscale_y=on&period=7"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:@"http" intoString:NULL];
[scanner scanUpToString:@"\"" intoString:&token];
NSLog(@"%@",token);
NSURL * imageURL = [NSURL URLWithString:token];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
_chartImage.image = image;
}

- (void) depthChart{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:@"http://waterdata.usgs.gov/va/nwis/uv/?dd_cd=07_00065&format=img_default&site_no=02037500&set_arithscale_y=on&period=7"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:@"http" intoString:NULL];
[scanner scanUpToString:@"\"" intoString:&token];
NSLog(@"%@",token);
NSURL * imageURL = [NSURL URLWithString:token];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
_chartImage.image = image;
}

- (void) progressAlert {
// initialize our Alert View window without any buttons
baseAlert=[[UIAlertView alloc]initWithTitle:@"Please wait,\ndownloading updates...." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];

// Display our Progress Activity view
[baseAlert show];

// create and add the UIActivity Indicator
UIActivityIndicatorView
*activityIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.center=CGPointMake(baseAlert.bounds.size.width
                                     / 2.0f,baseAlert.bounds.size.height-40.0f);

// initialize to tell our activity to start animating.
[activityIndicator startAnimating];
[baseAlert addSubview:activityIndicator];

// automatically close our window after 3 seconds has passed.
[self performSelector:@selector(showProgressDismiss)withObject:nil afterDelay:3.0f];

}
- (void) showProgressDismiss
{
[baseAlert dismissWithClickedButtonIndex:0 animated:NO];
}
@end

那么有人可以告诉我如何在所有这些东西加载时让我的 baseAlert 显示和关闭吗?

4

3 回答 3

2

使用 dispatch_group_t,一旦所有线程都完成,它们就可以调用 notify,如下所示:

        dispatch_group_t group = dispatch_group_create();
        dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
            [self doAnExpensiveOperation];
        });
        dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
            [self doAnotherExpensiveOperation];
        });
        dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{

            dispatch_async(dispatch_get_main_queue(), ^{

                // called when both background threads have finished.
                // Update UI elements here
            });

        });

优先:

dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            [self doAnotherExpensiveOperation];
        });
于 2013-07-02T00:22:13.080 回答
0

iOS与on应用相同的概念Android:如果您想要执行繁重的计算并且您希望应用程序具有响应性,请在后台线程上执行繁重的计算并且不要从后台线程访问 UI。iOS和之间的唯一区别Android是您可以在后台线程上执行任务的方式。Androidhas AsyncTasksor Loaders, iOShas NSOperations& NSOperationsQueue, GCD(我最喜欢的也是我认为最好的解决方案的大型中央调度)或者有一些performSelectorInBackground:我不喜欢的方法,因为在线程完成后更难返回对象。

所以我的建议是,看看GCD(还有很多其他教程),然后相应地更改你的代码,如果你在更改代码时遇到问题或者你有意外的行为,请回到 SO 并提出其他问题

于 2013-07-01T22:36:14.640 回答
0

好吧,为了简单明了,你可以告诉你的操作系统在另一个线程中执行一些代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //Insert your code here
});

全局队列意味着您将向 GCD 提交一个块,操作系统将在一个方便的线程中执行该块,除了主线程(您的 UI 运行的地方)。您必须注意,如果要更新 UI(例如隐藏警报或停止活动指示器),则需要在主线程 (main_queue) 中执行此操作。所以,我们经常使用的模板如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //Process your heavy code here.
    dispatch_async(dispatch_get_main_queue(), ^{
        //Update your UI here.
    });
});

如果您使用 ARC,这对于避免保留循环非常重要

正如 Apple 所说,您必须在块内使用弱引用self对于您在保留计数将增加的块内使用的任何 iVar 也是如此。

我建议@danypata 提出的教程,这是一个很好的教程。在同一个站点中,您可以找到很多有用的教程!!

祝您有美好的一天,希望对您有所帮助!

于 2013-07-02T00:18:01.540 回答