123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381 |
- //
- // MWPhoto.m
- // MWPhotoBrowser
- //
- // Created by Michael Waterfall on 17/10/2010.
- // Copyright 2010 d3i. All rights reserved.
- //
- //#import <SDWebImage/SDWebImageDecoder.h>
- #import <SDWebImage/SDWebImageManager.h>
- #import <SDWebImage/SDWebImageOperation.h>
- #import <AssetsLibrary/AssetsLibrary.h>
- #import "MWPhoto.h"
- #import "MWPhotoBrowser.h"
- #import <WFChatClient/WFCChatClient.h>
- #import "WFCUConfigManager.h"
- @interface MWPhoto () {
- BOOL _loadingInProgress;
- id <SDWebImageOperation> _webImageOperation;
- PHImageRequestID _assetRequestID;
- PHImageRequestID _assetVideoRequestID;
-
- }
- @property (nonatomic, strong) UIImage *image;
- @property (nonatomic, strong) NSURL *photoURL;
- @property (nonatomic, strong) PHAsset *asset;
- @property (nonatomic) CGSize assetTargetSize;
- - (void)imageLoadingComplete;
- @end
- @implementation MWPhoto
- @synthesize underlyingImage = _underlyingImage; // synth property from protocol
- #pragma mark - Class Methods
- + (MWPhoto *)photoWithImage:(UIImage *)image {
- return [[MWPhoto alloc] initWithImage:image];
- }
- + (MWPhoto *)photoWithURL:(NSURL *)url {
- return [[MWPhoto alloc] initWithURL:url];
- }
- + (MWPhoto *)photoWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
- return [[MWPhoto alloc] initWithAsset:asset targetSize:targetSize];
- }
- + (MWPhoto *)videoWithURL:(NSURL *)url {
- return [[MWPhoto alloc] initWithVideoURL:url];
- }
- #pragma mark - Init
- - (id)init {
- if ((self = [super init])) {
- self.emptyImage = YES;
- [self setup];
- }
- return self;
- }
- - (id)initWithImage:(UIImage *)image {
- if ((self = [super init])) {
- self.image = image;
- [self setup];
- }
- return self;
- }
- - (id)initWithURL:(NSURL *)url {
- if ((self = [super init])) {
- self.photoURL = url;
- [self setup];
- }
- return self;
- }
- - (id)initWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
- if ((self = [super init])) {
- self.asset = asset;
- self.assetTargetSize = targetSize;
- self.isVideo = asset.mediaType == PHAssetMediaTypeVideo;
- [self setup];
- }
- return self;
- }
- - (id)initWithVideoURL:(NSURL *)url {
- if ((self = [super init])) {
- self.videoURL = url;
- self.isVideo = YES;
- self.emptyImage = YES;
- [self setup];
- }
- return self;
- }
- - (void)setup {
- _assetRequestID = PHInvalidImageRequestID;
- _assetVideoRequestID = PHInvalidImageRequestID;
- }
- - (void)dealloc {
- [self cancelAnyLoading];
- }
- #pragma mark - Video
- - (void)setVideoURL:(NSURL *)videoURL {
- _videoURL = videoURL;
- self.isVideo = YES;
- }
- - (void)getVideoURL:(void (^)(NSURL *url))completion {
- if (_videoURL) {
- completion(_videoURL);
- } else if (_asset && _asset.mediaType == PHAssetMediaTypeVideo) {
- [self cancelVideoRequest]; // Cancel any existing
- PHVideoRequestOptions *options = [PHVideoRequestOptions new];
- options.networkAccessAllowed = YES;
- typeof(self) __weak weakSelf = self;
- _assetVideoRequestID = [[PHImageManager defaultManager] requestAVAssetForVideo:_asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
-
- // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ // Testing
- typeof(self) strongSelf = weakSelf;
- if (!strongSelf) return;
- strongSelf->_assetVideoRequestID = PHInvalidImageRequestID;
- if ([asset isKindOfClass:[AVURLAsset class]]) {
- completion(((AVURLAsset *)asset).URL);
- } else {
- completion(nil);
- }
-
- }];
- }
- }
- #pragma mark - MWPhoto Protocol Methods
- - (UIImage *)underlyingImage {
- return _underlyingImage;
- }
- - (void)loadUnderlyingImageAndNotify {
- NSAssert([[NSThread currentThread] isMainThread], @"This method must be called on the main thread.");
- if (_loadingInProgress) return;
- _loadingInProgress = YES;
- @try {
- if (self.underlyingImage) {
- [self imageLoadingComplete];
- } else {
- [self performLoadUnderlyingImageAndNotify];
- }
- }
- @catch (NSException *exception) {
- self.underlyingImage = nil;
- _loadingInProgress = NO;
- [self imageLoadingComplete];
- }
- @finally {
- }
- }
- // Set the underlyingImage
- - (void)performLoadUnderlyingImageAndNotify {
-
- // Get underlying image
- if (_image) {
-
- // We have UIImage!
- self.underlyingImage = _image;
- [self imageLoadingComplete];
-
- } else if (_photoURL) {
-
- // Check what type of url it is
- if ([[[_photoURL scheme] lowercaseString] isEqualToString:@"assets-library"]) {
-
- // Load from assets library
- [self _performLoadUnderlyingImageAndNotifyWithAssetsLibraryURL: _photoURL];
-
- } else if ([_photoURL isFileReferenceURL]) {
-
- // Load from local file async
- [self _performLoadUnderlyingImageAndNotifyWithLocalFileURL: _photoURL];
-
- } else {
-
- // Load async from web (using SDWebImage)
- [self _performLoadUnderlyingImageAndNotifyWithWebURL: _photoURL];
-
- }
-
- } else if (_asset) {
-
- // Load from photos asset
- [self _performLoadUnderlyingImageAndNotifyWithAsset: _asset targetSize:_assetTargetSize];
-
- } else {
-
- // Image is empty
- [self imageLoadingComplete];
-
- }
- }
- // Load from local file
- - (void)_performLoadUnderlyingImageAndNotifyWithWebURL:(NSURL *)url {
- [[WFCCIMService sharedWFCIMService] getAuthorizedMediaUrl:self.message.messageUid mediaType:Media_Type_IMAGE mediaPath:url.absoluteString success:^(NSString *authorizedUrl, NSString *backupAuthorizedUrl) {
- [self _performLoadUnderlyingImageAndNotifyWithWebURLWithAuthedUrl:[NSURL URLWithString:authorizedUrl]];
- } error:^(int error_code) {
- [self _performLoadUnderlyingImageAndNotifyWithWebURLWithAuthedUrl:url];
- }];
- }
- - (void)_performLoadUnderlyingImageAndNotifyWithWebURLWithAuthedUrl:(NSURL *)url {
- @try {
- SDWebImageManager *manager = [SDWebImageManager sharedManager];
- _webImageOperation = [manager loadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
- if (expectedSize > 0) {
- float progress = receivedSize / (float)expectedSize;
- NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithFloat:progress], @"progress",
- self, @"photo", nil];
- [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_PROGRESS_NOTIFICATION object:dict];
- }
- } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
- if (error) {
- MWLog(@"SDWebImage failed to download image: %@", error);
- }
- _webImageOperation = nil;
- self.underlyingImage = image;
- dispatch_async(dispatch_get_main_queue(), ^{
- [self imageLoadingComplete];
- });
- }];
- } @catch (NSException *e) {
- MWLog(@"Photo from web: %@", e);
- _webImageOperation = nil;
- [self imageLoadingComplete];
- }
- }
- // Load from local file
- - (void)_performLoadUnderlyingImageAndNotifyWithLocalFileURL:(NSURL *)url {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- @autoreleasepool {
- @try {
- self.underlyingImage = [UIImage imageWithContentsOfFile:url.path];
- if (!_underlyingImage) {
- MWLog(@"Error loading photo from path: %@", url.path);
- }
- } @finally {
- [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
- }
- }
- });
- }
- // Load from asset library async
- - (void)_performLoadUnderlyingImageAndNotifyWithAssetsLibraryURL:(NSURL *)url {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- @autoreleasepool {
- @try {
- ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
- [assetslibrary assetForURL:url
- resultBlock:^(ALAsset *asset){
- ALAssetRepresentation *rep = [asset defaultRepresentation];
- CGImageRef iref = [rep fullScreenImage];
- if (iref) {
- self.underlyingImage = [UIImage imageWithCGImage:iref];
- }
- [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
- }
- failureBlock:^(NSError *error) {
- self.underlyingImage = nil;
- MWLog(@"Photo from asset library error: %@",error);
- [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
- }];
- } @catch (NSException *e) {
- MWLog(@"Photo from asset library error: %@", e);
- [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
- }
- }
- });
- }
- // Load from photos library
- - (void)_performLoadUnderlyingImageAndNotifyWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
-
- PHImageManager *imageManager = [PHImageManager defaultManager];
-
- PHImageRequestOptions *options = [PHImageRequestOptions new];
- options.networkAccessAllowed = YES;
- options.resizeMode = PHImageRequestOptionsResizeModeFast;
- options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
- options.synchronous = false;
- options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
- NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithDouble: progress], @"progress",
- self, @"photo", nil];
- [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_PROGRESS_NOTIFICATION object:dict];
- };
-
- _assetRequestID = [imageManager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
- dispatch_async(dispatch_get_main_queue(), ^{
- self.underlyingImage = result;
- [self imageLoadingComplete];
- });
- }];
- }
- // Release if we can get it again from path or url
- - (void)unloadUnderlyingImage {
- _loadingInProgress = NO;
- self.underlyingImage = nil;
- }
- - (void)imageLoadingComplete {
- NSAssert([[NSThread currentThread] isMainThread], @"This method must be called on the main thread.");
- // Complete so notify
- _loadingInProgress = NO;
- // Notify on next run loop
- [self performSelector:@selector(postCompleteNotification) withObject:nil afterDelay:0];
-
- if(self.underlyingImage && [self.message.content isKindOfClass:[WFCCImageMessageContent class]]) {
- WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)self.message.content;
- if(!imgCnt.localPath.length) {
- UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
- NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:self.message.conversation mediaType:Media_Type_IMAGE];
- NSString *path = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"img%lld.jpg", recordTime]];
- NSData *imgData = UIImageJPEGRepresentation(self.underlyingImage, 0.85);
- if([imgData writeToFile:path atomically:YES]) {
- imgCnt.localPath = path;
- imgCnt.size = self.underlyingImage.size;
- if(!imgCnt.thumbnail || imgCnt.thumbnail == [WFCCIMService sharedWFCIMService].defaultThumbnailImage) {
- imgCnt.thumbnail = [WFCCUtilities generateThumbnail:self.underlyingImage withWidth:120 withHeight:120];
- }
- [[WFCCIMService sharedWFCIMService] updateMessage:self.message.messageId content:imgCnt];
- }
- }
- }
- }
- - (void)postCompleteNotification {
- [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_LOADING_DID_END_NOTIFICATION
- object:self];
- }
- - (void)cancelAnyLoading {
- if (_webImageOperation != nil) {
- [_webImageOperation cancel];
- _loadingInProgress = NO;
- }
- [self cancelImageRequest];
- [self cancelVideoRequest];
- }
- - (void)cancelImageRequest {
- if (_assetRequestID != PHInvalidImageRequestID) {
- [[PHImageManager defaultManager] cancelImageRequest:_assetRequestID];
- _assetRequestID = PHInvalidImageRequestID;
- }
- }
- - (void)cancelVideoRequest {
- if (_assetVideoRequestID != PHInvalidImageRequestID) {
- [[PHImageManager defaultManager] cancelImageRequest:_assetVideoRequestID];
- _assetVideoRequestID = PHInvalidImageRequestID;
- }
- }
- @end
|