iOS之通讯录和相册(Contacts Framework/Photos Framework)

因项目后期可能需要备份通讯录和相册,趁现在时间多,提前先了解下写个Demo。关于Contacts也有官方的视频,但视频是用Swift写的,让我也觉得要快速入手Swift了。

通讯录

通讯录要先导入�#import

添加联系人(由于我主要做备份,就写死了)

    CNMutableContact * contact = [[CNMutableContact alloc]init];
    contact.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"naruto.jpg"]);
    contact.givenName = @"steven";//设置名字
    contact.familyName = @"guo";//设置姓氏
    contact.emailAddresses = @[[CNLabeledValue labeledValueWithLabel:CNLabelWork value:@"[email protected]"]];//邮箱
    contact.phoneNumbers = @[[CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberiPhone value:[CNPhoneNumber phoneNumberWithStringValue:@"13999999999"]]];//电话
    /*其余属性我就不配置了
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *namePrefix;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *givenName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *middleName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *familyName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *previousFamilyName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *nameSuffix;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *nickname;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *phoneticGivenName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *phoneticMiddleName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *phoneticFamilyName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *organizationName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *departmentName;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *jobTitle;
    @property (copy, NS_NONATOMIC_IOSONLY) NSString *note;
    太多了,未完。。。
    */
    
    //地址
    CNMutablePostalAddress * homeAdress = [[CNMutablePostalAddress alloc]init];
    homeAdress.street = @"大街";
    homeAdress.city = @"深圳";
    homeAdress.state = @"中国";
    homeAdress.postalCode = @"518000";
    contact.postalAddresses = @[[CNLabeledValue labeledValueWithLabel:CNLabelHome value:homeAdress]];
    //生日
    NSDateComponents * birthday = [[NSDateComponents  alloc]init];
    birthday.day=4;
    birthday.month=2;
    birthday.year=1989;
    contact.birthday=birthday;
    
    CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
    //将创建的联系人添加到系统通讯录中
    [saveRequest addContact:contact toContainerWithIdentifier:nil];
    
    /*方法也有很多
    //添加一个联系人
    - (void)addContact:(CNMutableContact *)contact toContainerWithIdentifier:(nullable NSString *)identifier;
    //更新一个联系人
    - (void)updateContact:(CNMutableContact *)contact;
    //删除一个联系人
    - (void)deleteContact:(CNMutableContact *)contact;
    //添加一组联系人
    - (void)addGroup:(CNMutableGroup *)group toContainerWithIdentifier:(nullable NSString *)identifier;
    //更新一组联系人
    - (void)updateGroup:(CNMutableGroup *)group;
    //删除一组联系人
    - (void)deleteGroup:(CNMutableGroup *)group;
    //向组中添加子组
    - (void)addSubgroup:(CNGroup *)subgroup toGroup:(CNGroup *)group NS_AVAILABLE(10_11, NA);
    //在组中删除子组
    - (void)removeSubgroup:(CNGroup *)subgroup fromGroup:(CNGroup *)group NS_AVAILABLE(10_11, NA);
    //向组中添加成员
    - (void)addMember:(CNContact *)contact toGroup:(CNGroup *)group;
    //向组中移除成员
    - (void)removeMember:(CNContact *)contact fromGroup:(CNGroup *)group;
    */

    CNContactStore * store = [[CNContactStore alloc]init];
    [store executeSaveRequest:saveRequest error:nil];//保存前面创建的请求

跳转至系统通讯录

需导入#import

    CNContactPickerViewController * contactVC = [[CNContactPickerViewController alloc]init];
    [self presentViewController:contactVC animated:YES completion:nil];

比起之前的AddressBookFramework,这个简单的不要不要的。。。

规档

CNContactStore * stroe = [[CNContactStore alloc]init];
    CNContactFetchRequest * request = [[CNContactFetchRequest alloc]initWithKeysToFetch:@[CNContactIdentifierKey,CNContactFamilyNameKey,CNContactGivenNameKey,CNContactOrganizationNameKey,CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactPostalAddressesKey,CNContactImageDataKey]];
    NSMutableArray * arr = [@[] mutableCopy];
    [stroe enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        [arr addObject:contact];
    }];
    [NSKeyedArchiver archiveRootObject:arr toFile:@"/Users/Crazy_Steven/Desktop/contact.xml"];//规档到桌面

详细的可以看Demo.


相册

跳转至系统相册

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
[self presentViewController:picker animated:YES completion:nil];

备份相册

使用Photos框架,先#import

NSMutableArray *dataArray = [NSMutableArray array];
    
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc]init];
    
    PHFetchResult *smartAlbumsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:fetchOptions];
    /*第一个参数的枚举含义
     PHAssetCollectionTypeAlbum      //从 iTunes 同步来的相册,以及用户在 Photos 中自己建立的相册
     PHAssetCollectionTypeSmartAlbum //经由相机得来的相册
     PHAssetCollectionTypeMoment     //Photos 为我们自动生成的时间分组的相册
     */
    
    /*第二个参数的枚举含义
     PHAssetCollectionSubtypeAlbumRegular         //用户在 Photos 中创建的相册,也就是我所谓的逻辑相册
     PHAssetCollectionSubtypeAlbumSyncedEvent     //使用 iTunes 从 Photos 照片库或者 iPhoto 照片库同步过来的事件。然而,在iTunes 12 以及iOS 9.0 beta4上,选用该类型没法获取同步的事件相册,而必须使用AlbumSyncedAlbum。
     PHAssetCollectionSubtypeAlbumSyncedFaces     //使用 iTunes 从 Photos 照片库或者 iPhoto 照片库同步的人物相册。
     PHAssetCollectionSubtypeAlbumSyncedAlbum     //做了 AlbumSyncedEvent 应该做的事
     PHAssetCollectionSubtypeAlbumImported        //从相机或是外部存储导入的相册.
     
     PHAssetCollectionSubtypeAlbumMyPhotoStream   //用户的 iCloud 照片流
     PHAssetCollectionSubtypeAlbumCloudShared     //用户使用 iCloud 共享的相册
     
     PHAssetCollectionSubtypeSmartAlbumGeneric    //文档解释为非特殊类型的相册,主要包括从 iPhoto 同步过来的相册。
     PHAssetCollectionSubtypeSmartAlbumPanoramas  //相机拍摄的全景照片
     PHAssetCollectionSubtypeSmartAlbumVideos     //相机拍摄的视频
     PHAssetCollectionSubtypeSmartAlbumFavorites  //收藏文件夹
     PHAssetCollectionSubtypeSmartAlbumTimelapses //延时视频文件夹,同时也会出现在视频文件夹中
     PHAssetCollectionSubtypeSmartAlbumAllHidden  //包含隐藏照片或视频的文件夹
     PHAssetCollectionSubtypeSmartAlbumRecentlyAdded //相机近期拍摄的照片或视频
     PHAssetCollectionSubtypeSmartAlbumBursts     //连拍模式拍摄的照片,在 iPad mini 上按住快门不放就可以了,但是照片依然没有存放在这个文件夹下,而是在相机相册里。
     PHAssetCollectionSubtypeSmartAlbumSlomoVideos //Slomo 是 slow motion 的缩写,高速摄影慢动作解析,在该模式下,iOS 设备以120帧拍摄。不过我的 iPad mini 不支持,没法验证。
     PHAssetCollectionSubtypeSmartAlbumUserLibrary //相机相册,所有相机拍摄的照片或视频都会出现在该相册中,而且使用其他应用保存的照片也会出现在这里。
     
     
     PHAssetCollectionSubtypeAny                  //包含所有类型
     */
     //这里说明一下,必须要同步执行。。。否则你还没遍历完图片就规档完了
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //遍历相机胶卷
        [smartAlbumsFetchResult enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop) {
            
            if (![collection.localizedTitle isEqualToString:@"Videos"]) {
                NSArray *assets = [self GetAssetsInAssetCollection:collection];
                for (PHAsset * asset in assets) {
                    [[PHImageManager defaultManager]requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                        [dataArray addObject:imageData];
                    }];
                }
            }
        }];
        //遍历自定义相册
        PHFetchResult *smartAlbumsFetchResult1 = [PHAssetCollection fetchTopLevelUserCollectionsWithOptions:fetchOptions];
        [smartAlbumsFetchResult1 enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop) {
            
            NSArray *assets = [self GetAssetsInAssetCollection:collection];
            for (PHAsset * asset in assets) {
                [[PHImageManager defaultManager]requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                    [dataArray addObject:imageData];
                }];
            }
        }];
        [dataArray writeToFile:@"/Users/Crazy_Steven/Desktop/Photos.plist" atomically:YES];
    });
- (NSArray *)GetAssetsInAssetCollection:(PHAssetCollection *)assetCollection
{
    NSMutableArray *arr = [NSMutableArray array];
    
    PHFetchResult *result = [self GetFetchResult:assetCollection];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (((PHAsset *)obj).mediaType == PHAssetMediaTypeImage) {
            [arr addObject:obj];
        }
    }];
    return arr;
}

-(NSString *) FormatPhotoAlumTitle:(NSString *)title
{
    if ([title isEqualToString:@"All Photos"] || [title isEqualToString:@"Camera Roll"]) {
        return @"相机胶卷";
    }
    return nil;
}

-(PHFetchResult *)GetFetchResult:(PHAssetCollection *)assetCollection
{
    PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    return fetchResult;
    
}

具体效果还是看Demo,和通讯录的写到一起了,用的方法比较Low,不知道百度之类的云盘是怎么实现备份的,知道的也请大家告诉我,一同进步。。。

版权声明:本文为 Crazy Steven 原创出品,欢迎转载,转载时请注明出处!

你可能感兴趣的:(iOS之通讯录和相册(Contacts Framework/Photos Framework))