iOS功能 - 将图片或视图存入相册

将图片或视图存入相册

1 - 准备工作:配置 Info.plist 文件

 <key>NSPhotoLibraryUsageDescription</key>
 <string>需要您的同意,才能访问您的媒体资料库</string>

 <key>NSPhotoLibraryAddUsageDescription</key>
 <string>需要您的同意,才能访问您的媒体资料库</string>

2 - 代码示例

复制代码
  1 #import "ViewController.h"
  2 #import <Photos/Photos.h> // 引入文件
  3 @interface ViewController()
  4 
  5 @property(nonatomic,strong)UIImageView *testView; // 将要保存的图片
  6 @property(nonatomic,strong)PHAssetCollection *createCollection;// 相册
  7 
  8 @end
  9 
 10 
 11 @implementation ViewController
 12 
 13 - (void)viewDidLoad {
 14     [super viewDidLoad];
 15 
 16     // btn
 17     UIButton *nextBT = [UIButton buttonWithType:UIButtonTypeCustom];
 18     nextBT.frame = CGRectMake(60, 30, self.view.frame.size.width - 120, 40);
 19     [nextBT setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
 20     [nextBT setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
 21     [nextBT setTitle:@"存储测试" forState:UIControlStateNormal];
 22     nextBT.layer.cornerRadius = 8;
 23     nextBT.layer.masksToBounds  =  YES;
 24     nextBT.backgroundColor = [UIColor cyanColor];
 25     [nextBT addTarget:self action:@selector(saveView) forControlEvents:UIControlEventTouchUpInside];// 存储照片
 26     [self.view addSubview:nextBT];
 27 
 28     // 图片
 29     self.testView = [[UIImageView alloc] init];
 30     self.testView.backgroundColor = [UIColor redColor];
 31     self.testView.frame = CGRectMake((self.view.frame.size.width - 200)/2.0, 120, 200, 300);
 32     [self.view addSubview:self.testView];
 33 
 34 }
 35 
 36 
 37 // 将图片保存到系统相册
 38 -(void)saveView{
 39 
 40     UIImageWriteToSavedPhotosAlbum(self.testView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
 41 }
 42 
 43 -(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
 44 
 45     NSString *msg = nil ;
 46     if(error){
 47         msg = @"保存图片失败" ;
 48     }else{
 49         msg = @"保存图片成功" ;
 50     }
 51     NSLog(@"%@",msg);
 52 }
 53 
 54 
 55 // 将图片保存到系统相册: 使用 Photos 框架
 56 -(void)saveViewII{
 57 
 58     // 凡是涉及增删改的操作,均需要放在 performChanges 里面执行
 59     [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
 60         
 61         [PHAssetChangeRequest creationRequestForAssetFromImage:[self.testView image]];
 62     } completionHandler:^(BOOL success, NSError * _Nullable error) {
 63         
 64         if (error) {
 65             NSLog(@"%@",@"保存失败");
 66         } else {
 67             NSLog(@"%@",@"保存成功");
 68         }
 69     }];
 70 
 71 }
 72 
 73 //-------------------------------------------------------------------------------
 74 
 75 // 将 View 存入相册
 76 -(void)saveViewsInAnAlbum{
 77 
 78     NSError *error = nil;
 79     __block PHObjectPlaceholder *placeholder = nil;
 80 
 81     // 把 View  转换成 image 进行保存
 82     CGSize s = self.view.bounds.size;
 83     UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
 84     [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
 85     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 86     UIGraphicsEndImageContext();
 87 
 88     [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
 89         placeholder =  [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset;
 90     } error:&error];
 91 
 92     if (error) {
 93         NSLog(@"view 保存失败");
 94     }else {
 95         NSLog(@"view 保存成功");
 96     }
 97 }
 98 
 99 //-------------------------------------------------------------------------------
100 
101 // 将图片保存图片到自定义相册
102 -(void)movePicToMyAlbum{
103 
104     NSError *error = nil;
105     __block PHObjectPlaceholder *placeholder = nil;
106     
107     [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
108         
109         placeholder =  [PHAssetChangeRequest creationRequestForAssetFromImage:self.testView.image].placeholderForCreatedAsset;
110     } error:&error];
111     
112     if (error) {
113         
114         NSLog(@"保存失败");
115         return;
116     }
117 
118     // 搞一个相册
119     PHAssetCollection * assetCollection = [self createAlbumII];
120     if (assetCollection == nil) {
121         NSLog(@"创建相册失败");
122         return;
123     }
124 
125     // 方式 ①:将刚才保存到系统相册里面的图片转存到自定义相册,最新保存的图片排在最后面
126     [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
127         
128         PHAssetCollectionChangeRequest *requtes = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
129         [requtes addAssets:@[placeholder]];
130     } error:&error];
131 
132 //    // 方式 ②:最新保存的图片排在最前面
133 //    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
134 //
135 //        PHAssetCollectionChangeRequest *requtes = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
136 //        [requtes insertAssets:@[placeholder] atIndexes:[NSIndexSet indexSetWithIndex:0]];
137 //    } error:&error];
138 
139     if (error) {
140         NSLog(@"保存图片失败");
141     } else {
142         NSLog(@"保存图片成功");
143     }
144 }
145 
146 // 创建自定义相册
147 // 造成问题:如果我们一直点击保存图片按钮,则会重复创建多个相册,如何解决?参见 createAlbumII 方法
148 -(void)createAlbum{
149 
150     [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
151 
152         // 获取 app 名字,用作相册名
153         NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
154         // 创建相册
155         [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
156     } error:nil];
157 
158 }
159 
160 // 避免重复创建一个相册
161 -(PHAssetCollection*)createAlbumII{
162 
163     NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
164     // 查询所有自定义相册
165     PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
166 
167     self.createCollection = nil;
168     for (PHAssetCollection *collection in collections) {
169 
170         if ([collection.localizedTitle isEqualToString:title]) {
171             self.createCollection = collection;
172             break;
173         }
174     }
175 
176     // 相册没有被创建
177     if (self.createCollection == nil) {
178 
179         NSError *error = nil;
180 
181 //        // 方式 ①:创建相册
182 //        [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
183 //
184 //            [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];// 创建相册
185 //        } error:&error];
186 
187         // 方式 ②(推荐):创建相册
188         __block NSString *createCollectionID = nil;
189         [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
190             createCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
191         } error:&error];
192 
193         self.createCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createCollectionID] options:nil].firstObject;
194     }
195 
196     return _createCollection;
197 }
198 
199 
200 @end
复制代码

 

posted on   低头捡石頭  阅读(27)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示