iOS 6 - 当手势被识别且活动指示器未显示时,我的应用程序滞后。我需要做什么?

时间:2013-01-09 16:52:12

标签: ios uiwebview uigesturerecognizer uiactivityindicatorview

我添加了一个手势识别器(两个手指点击),用于检测用户何时按下UIWebView中的图像并调出UIActivityViewController来保存图像和其他内容。我的问题是,当我按下图像时会出现滞后(取决于图像大小可能有多大)以及我想要实现的是当用户双击图像时我想显示一个活动指示器,直到图像已准备好保存等...我可以补充一点,我认为问题出在这里'imageToBeSaved = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];'在我拿出那些代码后,没有更多的滞后。这是我的代码:

// adding gesture recognizer to "website" (which is a "UIWebView")
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
doubleTap.numberOfTouchesRequired = 2;
[website addGestureRecognizer:doubleTap];

// actions on gesture detect and call actionsOnImage for options
-(void) doubleTap :(UITapGestureRecognizer*) sender {
[loadingImageActivityIndicator startAnimating];
int scrollPositionY = [[self.website stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];
int scrollPositionX = [[self.website stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] intValue];

int displayWidth = [[self.website stringByEvaluatingJavaScriptFromString:@"window.outerWidth"] intValue];
CGFloat scale = website.frame.size.width / displayWidth;

CGPoint pt = [sender locationInView:self.website];
pt.x *= scale;
pt.y *= scale;
pt.x += scrollPositionX;
pt.y += scrollPositionY;

NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", pt.x, pt.y];
NSString *tagName = [self.website stringByEvaluatingJavaScriptFromString:js];

if ([tagName compare:@"IMG" options:NSCaseInsensitiveSearch]==NSOrderedSame) {
    NSLog(@"tagName was IMG");
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];
    NSString *urlToSave = [self.website stringByEvaluatingJavaScriptFromString:imgURL];
    NSURL *url = [NSURL URLWithString:urlToSave];
    imageToBeSaved = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    [website addSubview:loadingImageActivityIndicator];

    [self actionsOnImage];  // self made function with sharing capabilities (see below)
}

}

- (void) actionsOnImage {
[loadingImageActivityIndicator stopAnimating];

NSArray* dataToShare = [[NSArray alloc] initWithObjects:imageToBeSaved, nil];
UIActivityViewController* activityViewController =
[[UIActivityViewController alloc] initWithActivityItems:dataToShare
                                  applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:^{}];
}

1 个答案:

答案 0 :(得分:1)

异步加载图像。重新排列代码行,如下所示

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
     imageToBeSaved = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
     [self actionsOnImage];
});

[website addSubview:loadingImageActivityIndicator];