【问题标题】:URL of image after UIImageWriteToSavedPhotosAlbum in SwiftSwift 中 UIImageWriteToSavedPhotosAlbum 之后的图片 URL
【发布时间】:2015-05-14 14:24:35
【问题描述】:

在我用相机拍照后,我使用以下代码保存图像:

UIImageWriteToSavedPhotosAlbum(image, self,"image:didFinishSavingWithError:contextInfo:", nil)

这会将图像保存在相机胶卷中。此外,我想将 URL 保存到 Core Data 中保存的图像。是否可以检索 URL(或路径)以便我只需要保存这个 URL 而不是 Core Data 中的完整图像?

【问题讨论】:

标签: ios xcode swift ios8


【解决方案1】:

在阅读了很多用 ObjectivC 编写的答案后,我终于想出了如何用 Xcode 6.2 用 Swift 编写这个:

ALAssetsLibrary().writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!,
            completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
                println("\(path)")
        })

【讨论】:

  • 别忘了导入声明:import AssetsLibrary ;)
  • 注:自 iOS 9 起,此 API 已被弃用。正如 Tys 在 stackoverflow.com/a/4458451/171144 的评论中所说,“而是使用 PHPhotoLibrary 和“performChanges”方法将图像保存到设备。”
【解决方案2】:

这是我的组合..

保存图片:

    let imageData = NSData(data:UIImagePNGRepresentation(pickedimage))
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    var docs: String = paths[0] as! String
    let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
    let result = imageData.writeToFile(fullPath, atomically: true)

    print(fullPath)

获取图片:

    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
    if let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    {
        if paths.count > 0
        {
            if let dirPath = paths[0] as? String
            {
                let readPath = dirPath.stringByAppendingPathComponent("yourNameImg.png")
                let image    = UIImage(contentsOfFile: readPath)

                UploadImagePreview.image = image
            }
        }
    }

我们可以尝试使用 Photos Framework 来获取最后保存的图像。

    var fetchOptions: PHFetchOptions = PHFetchOptions()

    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

    var fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)

    if (fetchResult.firstObject != nil) {

        var lastAsset: PHAsset = fetchResult.lastObject as! PHAsset

        PHImageManager.defaultManager().requestImageForAsset(lastAsset, targetSize: self.UploadImagePreview.bounds.size, contentMode: PHImageContentMode.AspectFill, options: PHImageRequestOptions(), resultHandler: { (result, info) -> Void in

            self.UploadImagePreview.image = result

        })

    }

【讨论】:

  • 如果我们只需要一个对象,我们可以使用fetchOptions.fetchLimit = 1。还有顺序错了,应该是ascending: false
猜你喜欢
  • 2011-11-07
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多