How to get sandbox path and save pictures to album

Time:2020-10-15

Several ways to obtain directory in iPhone sandbox:

//Get sandbox home directory path 
NSString *homeDir = NSHomeDirectory(); 
//Get documents directory path 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docDir = [paths objectAtIndex:0]; 
//Get caches directory path 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
NSString *cachesDir = [paths objectAtIndex:0]; 
//Get TMP directory path 
NSString *tmpDir = NSTemporaryDirectory(); 
//Get a picture resource in the current package( apple.png )Path 
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"]; 
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];

There are three ways to save pictures to an album:

1. Use the uiimagewritetosavedphotosalbum function to save a picture to an album, such as:


- (void)loadImageFinished:(UIImage *)image
{
 UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
 NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

The first parameter is the picture object to be saved to the album

The second parameter is the target object of the callback after saving

The third parameter is to call back to the method of the target object after saving. The method declaration should be as shown in the code:


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

After the fourth parameter is saved, it is returned to the contextinfo parameter of the callback method intact.

2. Use the alassetslibrary class in the assetslibrary framework to implement. The specific codes are as follows:


- (void)loadImageFinished:(UIImage *)image
{
 __block ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
 [lib writeImageToSavedPhotosAlbum:image.CGImage metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
  NSLog(@"assetURL = %@, error = %@", assetURL, error);
  lib = nil;
 }];
}

Using the writeimagetosavedph of the alassetslibrary class otosAlbum:metadata : completionblock: method implementation. The first parameter is an object of cgimageref, which represents the image to be passed in. The second parameter is some properties of the image, which is not set here, so nil is passed in. The last completionblock is the callback after saving. In this callback, you can get the saved image path and the error information when saving failed.

be careful:Import is required when using this class AssetsLibrary.framework 。 Moreover, this class needs to be available above IOS 4.0, but it is marked as obsolete after IOS 9.0. Officially recommended Photos.framework This is the third method described below.

3. Use the phphotolibrary class of the photosframework to realize the function of saving to the album. The code is as follows:

- (void)loadImageFinished:(UIImage *)image
{
 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
   /Write pictures to album
   PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

  } completionHandler:^(BOOL success, NSError * _Nullable error) {
   NSLog(@"success = %d, error = %@", success, error);
 }];
}

In this example, perfo of phphotolibrary class is called first rmChanges:completionHandler : method, and then in its changeblock, pass in a picture object through the creationrequestforassetfromimage: method of the phasetchangerequest class to realize the function of saving to the album. Then the completionhandler will tell us whether the operation is successful or not.

Maybe someone needs to get the image’s phasset object after saving the album for subsequent operations (I happened to have a friend encounter this problem yesterday). Well, here, we improve the above example. After creating a phasetchangerequest, save its localidentifier attribute of the placeholderforcreatedasset property to an array. After the operation is completed, we can use this array to find the image object just added.

Look at the chestnuts:

- (void)loadImageFinished:(UIImage *)image
{
 NSMutableArray *imageIds = [NSMutableArray array];
  [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
   //Write pictures to album
   PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
   //Record the local logo, wait for the completion of the photo album to get the picture object
   [imageIds addObject:req.placeholderForCreatedAsset.localIdentifier];

  } completionHandler:^(BOOL success, NSError * _Nullable error) {
   NSLog(@"success = %d, error = %@", success, error);
   if (success)
   {
    //Take the picture object in the album after success
    __block PHAsset *imageAsset = nil;
    PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:imageIds options:nil];
    [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
     imageAsset = obj;
     *stop = YES;
    }];
    if (imageAsset)
    {
     //Load image data
     [[PHImageManager defaultManager] requestImageDataForAsset:imageAsset
       options:nil
       resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        NSLog("imageData = %@", imageData);
       }];
    }
   }
  }];
}

The way to get the sandbox path and save the pictures to the album is to share all the content with you. I hope it can give you a reference, and I hope you can support developpaer more.

Recommended Today

Think about open source project promoting rust search extension: quickly search rust documents in the browser address bar

Open source project name:Rust Search Extension Introduction to open source projects:Quick search for rust documents in the browser address barOpen source project type:teamProject creation time:2020 GitHub data:375 Star,18 ForkGitHub address:https://github.com/huhu/rust-search-extension Rust search extension is a plug-in that can quickly search rust documents, Crites, built-in properties and error codes in the browser address bar. It supports […]