iOS

IOS图片浏览器 - 基于UIWebview

2016-12-29  本文已影响472人  fengzila

最近项目需要实现一个图片浏览器的功能,要求也很常规,如下:
1、具有弹出、收起动画
2、在第N张图片收起图片浏览器时,容器内容要求定位在该图片的显示位置
3、流畅
最终实现效果如下:

2016-12-29 14_37_37.gif

由于项目中的文章页面使用H5渲染,所以解决思路如下:
1、js通知native所需要显示的图片url数组、index(当前点击的图片索引)、rect(当前点击图片的区域位置)
2、native在关闭图片浏览器时,通知js当前查看的图片index(js根据index跳转到网页对应位置),js回调native通知当前图片的rect(用于native播放收起动画)
期间遇到一个问题:
native并没有webview中已加载的图片资源,所以弹出动画难免出现加载过程,影响体验
解决方案如下:
注册NSURLProtocol,监听webview中所有的图片请求,并用SDWebImage缓存,以url为key,搞定。

- (void)startLoading {
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [self.request mutableCopy];
    [NSURLProtocol setProperty:@(YES) forKey:kProtocolHandledKey inRequest:request];
    
    __weak typeof(self) weakSelf = self;
    
    self.sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            return;
        }
        NSString *mimeType = response.MIMEType;
        if ([mimeType hasPrefix:@"image"]) {
            NSString *url = weakSelf.request.URL.absoluteString;
            SDImageCache *cache = [SDImageCache sharedImageCache];
            [cache storeImage:[UIImage imageWithData:data] forKey:url toDisk:NO];
        }
        
        [weakSelf.client URLProtocol:weakSelf didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];
        [weakSelf.client URLProtocol:weakSelf didLoadData:data];
        [weakSelf.client URLProtocolDidFinishLoading:weakSelf];
    }];
    [self.sessionTask resume];
}
上一篇下一篇

猜你喜欢

热点阅读