iOS8.0 使用Photos.framework對相簿的常用操作

來源:互聯網
上載者:User

標籤:orm   解析   enum   live   sse   detail   儲存   tail   info   

轉載自:http://blog.csdn.net/longitachi/article/details/50130957

1.判斷相簿存取權限

   首先我們訪問相簿,肯定有需要判斷是否有存取權限的時候,然後做出相應的操作

PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];if (status == PHAuthorizationStatusRestricted ||    status == PHAuthorizationStatusDenied) {    // 這裡便是無存取權限}
2.即時監聽相簿內部圖片變化

[[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];

當然,這個"self"是要遵守 PHPhotoLibraryChangeObserver 協議的 回調方法如下,不過這個地方是有一個坑的,就是這個回調是在一個子線程裡面,如果你想要對UI進行操作的話,則必須回調主線程
//相簿變化回調- (void)photoLibraryDidChange:(PHChange *)changeInstance{    dispatch_sync(dispatch_get_main_queue(), ^{        // your codes    });}
3.讀取相簿內所有圖片資源對相簿資源的相關操作,apple多都放在了 PHAsset內
#pragma mark - 擷取相簿內所有照片資源- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending{    NSMutableArray<PHAsset *> *assets = [NSMutableArray array];        PHFetchOptions *option = [[PHFetchOptions alloc] init];    //ascending 為YES時,按照照片的建立時間升序排列;為NO時,則降序排列    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];        PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];        [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {        PHAsset *asset = (PHAsset *)obj;        NSLog(@"照片名%@", [asset valueForKey:@"filename"]);        [assets addObject:asset];    }];        return assets;}
4.根據擷取的PHAsset對象,解析圖片
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];    //僅顯示縮圖,不控制品質顯示    /**     PHImageRequestOptionsResizeModeNone,     PHImageRequestOptionsResizeModeFast, //根據傳入的size,迅速載入大小相匹配(略大於或略小於)的映像     PHImageRequestOptionsResizeModeExact //精確的載入與傳入size相匹配的映像     */    option.resizeMode = PHImageRequestOptionsResizeModeFast;    option.networkAccessAllowed = YES;    //param:targetSize 即你想要的圖片尺寸,若想要原尺寸則可輸入PHImageManagerMaximumSize    [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {        //解析出來的圖片    }];
5.擷取所有智能相簿(即預設的,如“所有照片”“螢幕快照”等)
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];[smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop) {    NSLog(@"相簿名字:%@", collection.localizedTitle);}];

智能相簿的title不出意外都是英文,下面提供一個對應的中文名

- (NSString *)transformAblumTitle:(NSString *)title{    if ([title isEqualToString:@"Slo-mo"]) {        return @"慢動作";    } else if ([title isEqualToString:@"Recently Added"]) {        return @"最近添加";    } else if ([title isEqualToString:@"Favorites"]) {        return @"最愛";    } else if ([title isEqualToString:@"Recently Deleted"]) {        return @"最近刪除";    } else if ([title isEqualToString:@"Videos"]) {        return @"視頻";    } else if ([title isEqualToString:@"All Photos"]) {        return @"所有照片";    } else if ([title isEqualToString:@"Selfies"]) {        return @"自拍";    } else if ([title isEqualToString:@"Screenshots"]) {        return @"螢幕快照";    } else if ([title isEqualToString:@"Camera Roll"]) {        return @"相機菲林";    }    return nil;}

在項目plist設定檔中添加如下鍵,值設為YES,即可自動匹配手機系統語言,返回相簿名字。不需要進行上列判斷

Localized resources can be mixed YES//或者右鍵plist檔案Open As->Source Code 添加<key>CFBundleAllowMixedLocalizations</key><true/>

 

6.擷取所有使用者建立的相簿
PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {    NSLog(@"相簿名字:%@", collection.localizedTitle);}];
7.擷取每個相簿下的所有照片對象(PHAsset)
#pragma mark - 擷取指定相簿內的所有圖片- (NSArray<PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending{    NSMutableArray<PHAsset *> *arr = [NSMutableArray array];        PHFetchResult *result = [self fetchAssetsInAssetCollection:assetCollection ascending:ascending];    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {        [arr addObject:obj];//這個obj即PHAsset對象    }];    return arr;}
8.驗證該圖片是否在本地(若開啟了iCloud照片儲存,則圖片會定時上傳到網上,本地不存在)
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];    option.networkAccessAllowed = NO;    option.synchronous = YES;        __block BOOL isInLocalAblum = YES;        [[PHCachingImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {        isInLocalAblum = imageData ? YES : NO;    }];    return isInLocalAblum;

 9.擷取LivePhoto

PHLivePhotoRequestOptions *option = [[PHLivePhotoRequestOptions alloc] init];    option.version = PHImageRequestOptionsVersionCurrent;    option.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;    option.networkAccessAllowed = YES;        [[PHCachingImageManager defaultManager] requestLivePhotoForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:option resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nullable info) {        if (completion) completion(livePhoto, info);    }];

10.擷取Video

[[PHCachingImageManager defaultManager] requestPlayerItemForVideo:asset options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {        if (completion) completion(playerItem, info);    }];

 

iOS8.0 使用Photos.framework對相簿的常用操作

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.