iOS照片单选、多选、上传服务器、缓存、下载展示

文章目录

  • 概述
  • 具体步骤
      • 1.打开相机相册
      • 2. 选取照片,上传服务器,保存到本地缓存,及展示
      • 3.浏览原图,删除图片
      • 4.从服务器获取图片,本地缓存,缓存过大清空缓存。

概述

  • 图片单选效果图
    单选效果图
  • 图片多选效果图
    多选效果图
  • 有时候我们需要做一些选择照片上传展示的功能,其大概步骤为:
  1. 打开相机相册;
  2. 选取照片,获得照片后上传到服务器,上传成功后将照片保存到本地缓存中,并展示到九宫格中;
  3. 点击九宫格照片可以浏览原图,并且可以删除,在删除时去服务器删除照片删除成功后将本地缓存中的照片也删除;
  4. 当进入展示图片页面时,请求图片链接,根据链接截取图片名称然后去本地缓存区去查找有没有同名的照片,如果有从本地缓存中获取照片并展示,如果没有去服务器中下载,下载完成后保存到本地并展示;
  5. 为了防止缓存过大,我们可以设置一个缓存阈值,超过这个阈值就清除缓存。

具体步骤

1.打开相机相册

  • 打开相机和相册属于用户隐私,需要用户同意才可以所以需要在info.plist文件中添加两个key用来询问用户是否同意访问相机相册,这里调用相机是系统自带的,默认提示都为英文,可以修改英文标题为中文,如cancel换为取消等,也需要在info.plist文件中配置。
  1. 是否允许访问相册:Privacy - Photo Library Usage Description
  2. 是否允许访问相机:Privacy - Camera Usage Description
  3. 设置为中文:Localization native development region 设置为China.
  4. 设置Localized resources can be mixedYES,表示允许应用程序获取框架库内语言
  5. 是否允许将图片保存到相册: Privacy - Photo Library Additions Usage Description
    配置plist文件
  • 访问相机相册有一个专门的控制器类UIImagePickerController, 然后设置其sourceType 属性来判断是打开相机还是相册还是图片库:
  1. 图片库:UIImagePickerControllerSourceTypePhotoLibrary,
  2. 相机: UIImagePickerControllerSourceTypeCamera,
  3. 相册:UIImagePickerControllerSourceTypeSavedPhotosAlbum

访问相机相册:

- (void)rightBtnClick{UIAlertController * alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];__weak typeof(self)weakSelf = self;UIAlertAction * cameraAlert = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){//判断是否能够打开相机AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];//此应用程序没有被授权访问的照片数据。可能是家长控制权限 或者 用户已经明确否认了这一照片数据的应用程序访问if (status == AVAuthorizationStatusRestricted || status ==AVAuthorizationStatusDenied ) {[weakSelf showSelectMessgae:@"请设置允许访问相机"];}else{if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {UIImagePickerController * imagePickerC =  [[UIImagePickerController alloc]init];//设置资源类型为相机imagePickerC.sourceType = UIImagePickerControllerSourceTypeCamera;imagePickerC.delegate = self;[weakSelf presentViewController:imagePickerC animated:YES completion:nil];}else{NSLog(@"手机不支持拍照");}}}];UIAlertAction * photoLibraryAlert = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {//判断系统版本if ([UIDevice currentDevice].systemVersion.doubleValue >= 9.0) {PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){[weakSelf showSelectMessgae:@"请设置允许访问相册"];}else{if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {UIImagePickerController * imagePickerC =  [[UIImagePickerController alloc]init];//设置资源类型为图片资源库imagePickerC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;imagePickerC.delegate = self;[weakSelf presentViewController:imagePickerC animated:YES completion:nil];}else{}}}else{//9.0以后过期ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];if (status == kCLAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied){[weakSelf showSelectMessgae:@"请设置允许访问相册"];}else{if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {UIImagePickerController * imagePickerC =  [[UIImagePickerController alloc]init];//设置资源类型为图片资源库imagePickerC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;imagePickerC.showsCameraControls = NO;imagePickerC.delegate = self;[weakSelf presentViewController:imagePickerC animated:YES completion:nil];}else{NSLog(@"手机不支持相册");}}}}];UIAlertAction * cancelAlert =  [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];[alertC addAction:cameraAlert];[alertC addAction:photoLibraryAlert];[alertC addAction:cancelAlert];[self presentViewController:alertC animated:YES completion:nil];
}
- (void)showSelectMessgae:(NSString *)message{UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];UIAlertAction * action = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];if ([[UIApplication sharedApplication]canOpenURL:url]) {[[UIApplication sharedApplication]openURL:url];}}];UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];[alertC addAction:action];[alertC addAction:cancel];[self presentViewController:alertC animated:YES completion:nil];
}

2. 选取照片,上传服务器,保存到本地缓存,及展示

  • 获取图片成功失败会调用UIImagePickerController的代理方法,但要遵守两个协议UIImagePickerControllerDelegateUINavigationControllerDelegate

1.拍完照片,选择照片或者从图片库中选择照片后调用

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

2.取消时调用

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

3.保存照片时调用

 - (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void *)contextInfo

实现代理方法

#pragma mark UIImagePickerControllerDelegate
//拍完照片,选择照片或者从图片库中选择照片后调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{__weak typeof(self)weakSelf = self;[picker dismissViewControllerAnimated:YES completion:^{UIImage * loadImage = [info valueForKey:UIImagePickerControllerOriginalImage];//获得原始图片//高保真压缩图片,可以压缩图片但是图片质量基本没有损失,第二个参数即图片质量参数self.iamgeData = UIImageJPEGRepresentation(loadImage, 0.3);weakSelf.upFileType = @"jpeg";NSDateFormatter * dfm = [[NSDateFormatter alloc]init];dfm.dateFormat = @"yyyyMMddHHmmsssss";weakSelf.upFileName = [NSString stringWithFormat:@"%@_%@.%@",self.flowId,[dfm stringFromDate:[NSDate date]],weakSelf.upFileType];//上传到服务器[weakSelf upLoadPhoto];}];
}
//取消时调用
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{[picker dismissViewControllerAnimated:YES completion:nil];printf("取消");
}
//保存到相册
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{if (error != nil) {UIAlertView *fail = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];[fail show];NSLog(@"%@",error);}else{UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"保存成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];[alert show];[self.view addSubview:alert];}
}

图片上传成功保存到本地缓存

//上传照片到服务器
- (void)upLoadPhoto{NSMutableDictionary * parameters = [NSMutableDictionary dictionary];[parameters setValue:[LoginUser shareLoginUser].loginId forKey:@"loginId"];[parameters setValue:[LoginUser shareLoginUser].orgNo forKey:@"orgNo"];[parameters setValue:self.flowId forKey:@"flowId"];[parameters setValue:self.upFileType forKey:@"upFileType"];[parameters setValue:self.upFileName forKey:@"upFileName"];NSMutableDictionary * dict = [NSMutableDictionary dictionary];[dict setValue:self.iamgeData forKey:@"upFile"];[dict setValue:@"upFile" forKey:@"name"];[dict setValue:self.upFileName forKey:@"upFileName"];[dict setValue:[NSString stringWithFormat:@"image/%@",self.upFileType] forKey:@"upFileType"];NSArray* fileArray = [NSArray arrayWithObject:dict];__weak typeof(self)weakSelf = self;[[IDataHttpRequest sharedRequest]upLoadFileWithUrlStr:@"actionSh/Order!commitImages.action" parameters:parameters andFileArray:fileArray andDataKey:@"upFile" nameKey:@"name" fileNameKey:@"upFileName" mimeTypeKey:@"upFileType" isShowRequestAnimation:YES success:^(NSDictionary *returnDic) {//上传成功后保存到本地数组中NSMutableDictionary * dic = [NSMutableDictionary dictionary];UIImage * image = [UIImage imageWithData:weakSelf.iamgeData];[dic setValue:image forKey:IMAGE];[dic setValue:weakSelf.upFileName forKey:IMAGENAME];[weakSelf.dataSource addObject:dic];//保存到本地缓存BOOL isSuccess = [weakSelf.iamgeData writeToFile:[weakSelf filePathWithIamgeName:weakSelf.upFileName] atomically:YES];//刷新collectionView[weakSelf.collectionView reloadData];} error:^(NSString *msg) {}];
}

创建缓存路径

- (NSString *)filePathWithIamgeName:(NSString *)imageName{//NSCachesDirectory,NSDocumentDirectory//获取缓存路NSString * cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;//在缓存路径后面拼接保存图片的文件夹路劲NSString * filePath = [cachePath stringByAppendingPathComponent:@"OrederImage"];//如果该文件夹路径不存在就创建该文件夹if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]) {[[NSFileManager defaultManager]createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];}DLog(@"imagePath : %@",[filePath stringByAppendingPathComponent:imageName]);//如果用图片就返回图片路径,没有就返回保存图片文件夹路径if (imageName) return [filePath stringByAppendingPathComponent:imageName];else return filePath;
}

九宫格展示图片

//创建流水布局
UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
//设置每个item的size
layout.itemSize = CGSizeMake(ITEMWITH, ITEMWITH);
//初始化collectionViewself.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(lineV.frame)+5, self.view.bounds.size.width - 20, self.view.bounds.size.height - CGRectGetMaxY(lineV.frame)-5) collectionViewLayout: layout];self.collectionView.dataSource = self;self.collectionView.delegate = self;self.collectionView.backgroundColor = [UIColor whiteColor];//这里用的是xib,需要注册一下id[self.collectionView registerNib:[UINib nibWithNibName:@"AlbumCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"AlbumCollectionViewCELL"];[self.view addSubview:self.collectionView];

实现数据源和代理方法

#pragma mark UICollectionViewDataSourceAndUICollectionViewDelegate-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{return self.dataSource.count;
}-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{AlbumCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AlbumCollectionViewCELL" forIndexPath:indexPath];NSDictionary * dict = self.dataSource[indexPath.row];//如果本地缓存中有就去缓存中获取图片if ([self.dataSource[indexPath.row] valueForKey:IMAGE]) {cell.imageV.image = [dict valueForKey:IMAGE];}else{//没有就去服务器中下载图片cell.imageV.image = self.placeholderImage;[self requestImageWithIndex:indexPath];}return cell;
}
//这个是两行cell之间的间距(上下行cell的间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{return 10;
}//两个cell之间的间距(同一行的cell的间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{return 10;
}

3.浏览原图,删除图片

点击展示原图

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{NSLog(@"%@",indexPath);NSMutableArray * imageArr = [NSMutableArray array];for (NSDictionary * dic in self.dataSource) {if ([dic valueForKey:@"image"]) {[imageArr addObject:[dic valueForKey:@"image"]];}}if (imageArr.count<self.dataSource.count)return;ShowBigPhotoViewController * showbigVC = [[ShowBigPhotoViewController alloc]init];//设置要展示的照片数据源showbigVC.imageArray = imageArr;//选中的是第几张照片,默认展示第几张,便于左右滑动时展示前后的照片showbigVC.index = indexPath.row;showbigVC.delegate = self;//是否能够删除(是否有删除按钮)showbigVC.isCanDelete = self.isUpload;[self presentViewController:showbigVC animated:YES completion:nil];
}

展示大图

#import "ShowBigPhotoViewController.h"- (void)viewDidLoad {[super viewDidLoad];self.view.backgroundColor = [UIColor blackColor];[self.view addSubview:self.backBtn];if (self.isCanDelete) {[self.view addSubview:self.deleteBtn];}[self.view addSubview:self.scrollV];//设置contentSize的宽度为scrollV宽度乘照片张数减去一个间距10(不减去10最后一张往右边滑动时会出现间距)self.scrollV.contentSize = CGSizeMake(self.scrollV.bounds.size.width * self.imageArray.count - GAP, self.scrollV.bounds.size.height);//遍历图片数组设置展示照片for (int i = 0; i < self.imageArray.count; i++) {UIImage * image = self.imageArray[i];//宽度为屏幕宽度,高度为图片宽高比计算CGFloat height = self.scrollV.bounds.size.width * (image.size.height/image.size.width);UIImageView * iamgev = [[UIImageView alloc]initWithFrame:CGRectMake(i * self.scrollV.bounds.size.width, 0, IMGAEWIDTH, height)];iamgev.image = image;[self.scrollV addSubview:iamgev];}//设置偏移量展示点击过的照片[self.scrollV setContentOffset:CGPointMake(self.index * self.scrollV.bounds.size.width , 0) animated:YES];
}-(UIScrollView *)scrollV{if (!_scrollV) {//_scrollV宽度为屏幕宽度加上间距是为了分页_scrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 60, IMGAEWIDTH + GAP, self.view.bounds.size.height - 60)];_scrollV.pagingEnabled = YES;_scrollV.showsVerticalScrollIndicator = NO;_scrollV.showsHorizontalScrollIndicator = NO;_scrollV.delegate = self;_scrollV.bounces = NO;//        _scrollV.clipsToBounds = NO;}return _scrollV;
}

删除图片

//删除照片需要去服务器中把改图片删除
- (void)deletePhotoWithIndex:(NSInteger)index{NSMutableDictionary * parameters = [NSMutableDictionary dictionary];[parameters setValue:[LoginUser shareLoginUser].loginId forKey:@"loginId"];[parameters setValue:[LoginUser shareLoginUser].orgNo forKey:@"orgNo"];[parameters setValue:self.flowId forKey:@"flowId"];NSDictionary * dict = self.dataSource[index];[parameters setValue:[dict valueForKey:IMAGENAME] forKey:@"upFileName"];__weak typeof(self)weakSelf = self;__block typeof(dict)blockDict = dict;[[IDataHttpRequest sharedRequest]requestDataWithUrlStr:@"actionSh/Order!deleteImages.action" parameters:parameters isShowRequestAnimation:YES success:^(NSDictionary *returnDic){//删除成功就给个提示UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"提示" message:[returnDic valueForKeyPath:@"state.msg"] preferredStyle:UIAlertControllerStyleAlert];UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];[alertC addAction:cancel];[weakSelf presentViewController:alertC animated:YES completion:nil];NSString * imagename = [blockDict valueForKey:IMAGENAME];//本地缓存中也删除if ([[NSFileManager defaultManager]fileExistsAtPath:[weakSelf filePathWithIamgeName:imagename]]) {[[NSFileManager defaultManager]removeItemAtPath:[weakSelf filePathWithIamgeName:imagename] error:nil];}[weakSelf.dataSource removeObjectAtIndex:index];[weakSelf.collectionView reloadData];} error:^(NSString *msg) {}];
}

4.从服务器获取图片,本地缓存,缓存过大清空缓存。

请求照片并且本地做缓存

//请求图片
- (void)requestData{//获取本地图片缓存大小,超过50M就清空缓存CGFloat CacheSize = [self readCacheSize];DLog(@"缓存:%lf M",CacheSize);if (CacheSize > 50) {[self clearFile];}NSMutableDictionary * parameters = [NSMutableDictionary dictionary];[parameters setValue:[LoginUser shareLoginUser].loginId forKey:@"loginId"];[parameters setValue:[LoginUser shareLoginUser].orgNo forKey:@"orgNo"];[parameters setValue:self.flowId forKey:@"flowId"];[[IDataHttpRequest sharedRequest]requestDataWithUrlStr:@"actionSh/Order!getImgList.action" parameters:parameters isShowRequestAnimation:YES success:^(NSDictionary *returnDic) {NSArray * array = [returnDic valueForKey:@"imgList"];for (NSDictionary * dict in array) {NSMutableDictionary * dic = [NSMutableDictionary dictionary];[dic setValue:[dict valueForKey:IMAGEURL] forKey:IMAGEURL];[dic setValue:[dict valueForKey:@"fileName"] forKey:IMAGENAME];//通过图片名称判断本地缓存中又没改图片,有就从本地读缓存文件if ([[NSFileManager defaultManager] fileExistsAtPath:[self filePathWithIamgeName:[dic valueForKey:IMAGENAME]]]) {NSData * imageData = [NSData dataWithContentsOfFile:[self filePathWithIamgeName:[dic valueForKey:IMAGENAME]]];UIImage * image = [UIImage imageWithData:imageData];if (image) {[dic setValue:image forKey:IMAGE];}}[self.dataSource addObject:dic];}[self.collectionView reloadData];} error:^(NSString *msg) {}];
}

计算缓存大小

//1. 获取缓存文件的大小
-(float)readCacheSize{NSString *cachePath = [self filePathWithIamgeName:nil];return [ self folderSizeAtPath :cachePath];
}//2.遍历文件夹获得文件夹大小,返回多少 M
- (float) folderSizeAtPath:( NSString *) folderPath{NSFileManager * manager = [NSFileManager defaultManager];if (![manager fileExistsAtPath :folderPath]) return 0 ;NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];NSString * fileName;long long folderSize = 0 ;while ((fileName = [childFilesEnumerator nextObject]) != nil ){//获取文件全路径NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];folderSize += [ self fileSizeAtPath :fileAbsolutePath];}return folderSize/( 1024.0 * 1024.0);
}//3.计算单个文件的大小
- (long long) fileSizeAtPath:( NSString *) filePath{NSFileManager * manager = [NSFileManager defaultManager];if ([manager fileExistsAtPath :filePath]){return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];}return 0;
}

清除缓存

- (void)clearFile
{NSString * cachePath = [self filePathWithIamgeName:nil];//[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];//NSLog ( @"cachpath = %@" , cachePath);for ( NSString * p in files) {NSError * error = nil ;//获取文件全路径NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {[[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];}}
}

#照片多选上传及展示

  • 类似于微信朋友圈的图片多选上传还是比较麻烦的,这里需要引用第三方的一个框架TZImagePickerController,
  • 主要步骤:导入TZImagePickerController框架,初始化TZImagePickerController控制器,设置相关属性,如果用代理方法获取返回的图片等信息,还要遵守TZImagePickerControllerDelegate协议,实现- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto代理方法,也可以用block;
  • 相关示例代码
    初始化设置属性:
//当从图片资源库中获取数据时
UIAlertAction * photoLibraryAlert = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {//判断系统版本if ([UIDevice currentDevice].systemVersion.doubleValue >= 9.0) {PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){[weakSelf showSelectMessgae:@"请设置允许访问相册"];}else{if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {//最大可选五张,每行显示三张照片TZImagePickerController *imagePick = [[TZImagePickerController alloc]initWithMaxImagesCount:5 columnNumber:3 delegate:self pushPhotoPickerVc:YES];imagePick.allowPreview = NO;//影藏预览按钮imagePick.showSelectedIndex = YES;//显示照片中的选中编号imagePick.showPhotoCannotSelectLayer = YES;//添加覆盖层imagePick.allowPickingVideo = NO;//不能选择视频imagePick.allowTakePicture = NO;//影藏内包拍照按钮imagePick.preferredLanguage = @"zh-Hans";//设置语言无为汉语简体[weakSelf presentViewController:imagePick animated:YES completion:nil];}else{NSLog(@"没有设置访问权限");}}}else{//iOS9.0以前ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];if (status == kCLAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied){[weakSelf showSelectMessgae:@"请设置允许访问相册"];}else{if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {TZImagePickerController *imagePick = [[TZImagePickerController alloc]initWithMaxImagesCount:5 columnNumber:3 delegate:self pushPhotoPickerVc:YES];imagePick.allowPreview = NO;//影藏预览按钮imagePick.showSelectedIndex = YES;//显示照片中的选中编号imagePick.showPhotoCannotSelectLayer = YES;//添加覆盖层imagePick.allowPickingVideo = NO;//不能选择视频imagePick.allowTakePicture = NO;//影藏内包拍照按钮imagePick.preferredLanguage = @"zh-Hans";//设置语言无为汉语简体[weakSelf presentViewController:imagePick animated:YES completion:nil];}else{NSLog(@"手机不支持相册");}}}}];

实现代理方法:

# pragma mark TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{if (photos){//photos:返回选中的图片数组//assets:返回返回图片信息的数组//isSelectOriginalPhoto:返回的是否是原图self.photoFileArray  = [NSMutableArray array];for (int i = 0; i < photos.count; i++) {NSMutableDictionary * dict = [NSMutableDictionary dictionary];UIImage * iamge = photos[i];NSData * iamgeData;if (isSelectOriginalPhoto)iamgeData  = UIImageJPEGRepresentation(iamge, 0.2);elseiamgeData  = UIImageJPEGRepresentation(iamge, 0.5);//图片数据[dict setValue:iamgeData forKey:@"data"];[dict setValue:@"upFile" forKey:@"name"];NSDateFormatter * dfm = [[NSDateFormatter alloc]init];dfm.dateFormat = @"yyyyMMddHHmmsssss";//设置保存到服务器中的图片名称NSString * upFileName = [NSString stringWithFormat:@"%@_%@%d.%@",self.flowId,[dfm stringFromDate:[NSDate date]],i,@"jpeg"];[dict setValue:upFileName forKey:@"upFileName"];//设置类型[dict setValue:[NSString stringWithFormat:@"image/jpeg"] forKey:@"upFileType"];[self.photoFileArray addObject:dict];}//上传服务器[self upLoadPhoto];}
}

#iOS访问用户隐私时在info.plist文件询问用户是否统一访问的常用key

NSAppleMusicUsageDescriptionApp需要您的同意,才能访问媒体资料库NSBluetoothPeripheralUsageDescriptionApp需要您的同意,才能访问蓝牙NSCalendarsUsageDescriptionApp需要您的同意,才能访问日历NSCameraUsageDescriptionApp需要您的同意,才能访问相机NSHealthShareUsageDescriptionApp需要您的同意,才能访问健康分享NSHealthUpdateUsageDescriptionApp需要您的同意,才能访问健康更新 NSLocationAlwaysUsageDescriptionApp需要您的同意,才能始终访问位置NSLocationUsageDescriptionApp需要您的同意,才能访问位置NSLocationWhenInUseUsageDescriptionApp需要您的同意,才能在使用期间访问位置NSMicrophoneUsageDescriptionApp需要您的同意,才能访问麦克风NSMotionUsageDescriptionApp需要您的同意,才能访问运动与健身NSPhotoLibraryUsageDescriptionApp需要您的同意,才能访问相册NSRemindersUsageDescriptionApp需要您的同意,才能访问提醒事项NSPhotoLibraryAddUsageDescription允许保存图片到相册


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部