Get the filename of image saved to photos album

大憨熊 提交于 2019-11-29 13:39:05
extension PHPhotoLibrary {

    func save(imageData: Data, withLocation location: CLLocation?) -> Promise<PHAsset> {
        var placeholder: PHObjectPlaceholder!
        return Promise { fullfil, reject in
            performChanges({
                let request = PHAssetCreationRequest.forAsset()
                request.addResource(with: .photo, data: imageData, options: .none)
                request.location = location
                placeholder = request.placeholderForCreatedAsset
            }, completionHandler: { (success, error) -> Void in
                if let error = error {
                    reject(error)
                    return
                }

                guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: .none).firstObject else {
                    reject(NSError())
                    return
                }

                fullfil(asset)
            })
        }
    }
}

I think you can do this with PHPhotoLibrary and PHObjectPlaceholder.

You just saved image programmatically, so you can get the image from camera and save it with your path:

//save image in Document Derectory
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];
      NSLog(@"Get Path : %@",documentsDirectory);

      //create Folder if Not Exist
      NSError *error = nil;
      NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/YourFolder"];

      if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

      NSString *yourPhotoName=@"YourPhotoName";
      NSString* path= [dataPath stringByAppendingString:[NSString stringWithFormat:@"/%@.png",yourPhotoName]];
      NSData* imageData = UIImagePNGRepresentation(imageToSaved); //which got from camera

      [imageData writeToFile:path atomically:YES];

      imagePath = path;
      NSLog(@"Save Image Path : %@",imagePath);
mmd1080

Maybe this is a different approach but here's what I'm doing in my app and I'm satisfied with it:

func saveImage(image: UIImage, name: String) {

    var metadata = [AnyHashable : Any]()
    let iptcKey = kCGImagePropertyIPTCDictionary as String
    var iptcMetadata = [AnyHashable : Any]()

    iptcMetadata[kCGImagePropertyIPTCObjectName as String] = name
    metadata[iptcKey] = iptcMetadata

    let library = ALAssetsLibrary()

    library.writeImage(toSavedPhotosAlbum: image.cgImage, metadata: metadata) { url, error in

        // etc...
    }
}

If you don't want to use ALAssetsLibrary, you'll probably be interested in this answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!