【问题标题】:Get the filename of image saved to photos album获取保存到相册的图片文件名
【发布时间】:2017-05-04 19:19:21
【问题描述】:

在现代 iOS (2017) 中,

这实际上是我知道的唯一方法将图像保存到 iOS 照片系统,并获取文件名/路径。

import UIKit
import Photos

func saveTheImage... () {

    UIImageWriteToSavedPhotosAlbum(yourUIImage, self,
        #selector(Images.image(_:didFinishSavingWithError:contextInfo:)),
        nil)
}

func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    guard error == nil else {
        print("Couldn't save the image!")
        return
    }
    doGetFileName()
}

func doGetFileName() {
    let fo: PHFetchOptions = PHFetchOptions()
    fo.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    let r = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fo)
    if let mostRecentThingy = r.firstObject {

        PHImageManager.default().requestImageData(
            for: mostRecentThingy,
            options: PHImageRequestOptions(),
            resultHandler: { (imagedata, dataUTI, orientation, info) in

                if info!.keys.contains("PHImageFileURLKey") {
                    let path = info!["PHImageFileURLKey"] as! NSURL

                    print("Holy cow. The path is \(path)")
                }
                else { print("bizarre problem") }
            })

    }
    else { print("unimaginable catastrophe") }
}

问题在于它在赛道条件下失败。

这非常笨拙,而且在很多方面看起来都令人担忧。

今天真的要走吗?

【问题讨论】:

  • 你真的需要这个网址吗?是否也可以使用相关PHObjectlocalIdentifier 属性?

标签: ios image ios10


【解决方案1】:
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)
            })
        }
    }
}

我认为您可以使用 PHPhotoLibraryPHObjectPlaceholder 来做到这一点。

【讨论】:

【解决方案2】:

您刚刚以编程方式保存了图像,因此您可以从相机中获取图像并使用您的路径保存:

//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);

【讨论】:

  • Hi Dong,我尝试发现路径如果它在Apple相册系统中
  • @Fattie:我用这个代码尝试了模拟器:============== - (void)imagePickerController:(UIImagePickerController )picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL]; NSLog(@"图片地址 %@", localUrl.absoluteString); } ====== 并得到类似:图片网址 assets-library://asset/asset.JPG?id=ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext=JPG 告诉我你是否需要它。 ^^
【解决方案3】:

也许这是一种不同的方法,但这是我在我的应用中所做的,我对此感到满意:

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...
    }
}

如果您不想使用 ALAssetsLibrary,您可能会对 this answer 感兴趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多