Search code examples
iosobjective-calassetslibraryios9.1phphotolibrary

How to save images into specific folder in iOS 9.0


Already have answers, for saving images into specific folder by using ALAssetsLibrary. But it is deprecated in iOS 9.0 and giving warning "Use PHPhotoLibrary from the Photos framework instead".

When i change ALAssetsLibrary into PHPhotoLibrary getting the error at this point.

    [self.library saveImage:image toAlbum:@"myAlbum" withCompletionBlock:^(NSError *error) {
    if (error!=nil) {
        NSLog(@"Big error: %@", [error description]);
    }
}];

*error

 No visible @interface for 'PHPhotoLibrary' declares the selector 'saveImage:toAlbum:withCompletionBlock:' 

How to save images into specific folder By Using PHPhotoLibrary (or) any other solutions.

Thank you in advance.


Solution

  • I have not used PHPhotoLibrary yet but I know the old school way of saving photos in Obj-C using the local documents directory:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = paths.firstObject;
    NSData *imageData = UIImagePNGRepresentation(image);
    
    NSString *imagePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,imageFolder];
    
    BOOL isDir;
    NSFileManager *fileManager= [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:imagePath isDirectory:&isDir])
        if(![fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:NULL])
            NSLog(@"Error: folder creation failed %@", documentsDirectory);
    
    [[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@/%@", imagePath, imageName] contents:nil attributes:nil];
    [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", imagePath, imageName] atomically:YES];
    

    To retrieve that image from the NSDocumentDirectory:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = paths.firstObject;
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentDirectory, imagePath]; // image path is same as above
    if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
        UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
        return image;
    } else {
        return nil;
    }