我正在尝试为用户提供照片库中图像的选择。因此,我UIImagePickerController用于选择。但是在文件系统中获取其初始URL会带来一个问题(我需要CKAsset)。
UIImagePickerController
CKAsset
我的代码。
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL let path = imageURL.path! let imageName = path.lastPathComponent let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentDirectory = paths.first as String! let localPath = documentDirectory + "/" + imageName let imageData = NSData(contentsOfFile: localPath)! let image = UIImage(data: imageData)! picker.dismissViewControllerAnimated(true, completion: nil) }
imageURL 有点神秘。它描述了资产URL,但没有描述文件系统中的一个。它看起来像:assets- library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG。
assets- library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG
根据该逻辑 路径 是/asset.JPG其中asset.JPG是所述图像的名称。
/asset.JPG
asset.JPG
然后,我访问我的Documents文件夹并尝试在其中找到带有路径的文件:
/Users/Eugene/Library/Developer/CoreSimulator/Devices/3C5E9A23-8220-4B37-BD14-F1E42EEC2C7C/data/Containers/Data/Application/20EBAAE2-6C6F-4651-A48F-16A222CCB3A2/Documents/asset.JPG
也是隐秘的,但对于不存在的图像似乎是一条真实的路径……找不到具有该路径的图像。这让我恶心。
我是否必须从头开始保存图像?还是还有其他路要走?
我已经浏览了一些使用 AssetsLibrary API的教程,但是没有发现有用的解决方案。先感谢您!
好的,我已经解决了问题。
您所要做的只是简单地抓取图像(info[UIImagePickerControllerOriginalImage] as UIImage)并保存到给定目录。如果您只需要保存1张图片,那么效果很好。下面的代码ID。
info[UIImagePickerControllerOriginalImage] as UIImage
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL let imageName = imageURL.path!.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String let localPath = documentDirectory.stringByAppendingPathComponent(imageName) let image = info[UIImagePickerControllerOriginalImage] as UIImage let data = UIImagePNGRepresentation(image) data.writeToFile(localPath, atomically: true) let imageData = NSData(contentsOfFile: localPath)! let photoURL = NSURL(fileURLWithPath: localPath) let imageWithData = UIImage(data: imageData)! picker.dismissViewControllerAnimated(true, completion: nil) }