0

我添加了一个手势识别器(两指点击),它检测用户何时按下 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:^{}];
}
4

1 回答 1

1

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

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

[website addSubview:loadingImageActivityIndicator];
于 2013-01-09T17:08:01.487 回答