2015-01-31 2 views
6

사진 라이브러리에서 사용자가 선택한 이미지를 제공하려고합니다. 따라서 저는 UIImagePickerController을 사용하고 있습니다. 그러나 파일 시스템에서 초기 URL을 얻는 데 문제가 있습니다 (이 URL은 CKAsset에 필요합니다).UIImagePickerController에서 UIImage의 URL을 가져 오는 중

내 코드.

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) 

} 

이미지 URL 좀 애매하다. 애셋 URL은 설명하지만 파일 시스템에는 애셋 URL이 없습니다. 그리고 모양은 다음과 같습니다 : assets-library://asset/asset.JPG?id=B6C0A21C-07C3-493D-8B44-3BA4C9981C25&ext=JPG.

이 논리에 따르면 경로/asset.JPG입니다. 여기서 asset.JPG은 이미지의 이름입니다. 그런 다음

내 문서 폴더에 액세스하고이 경로에 파일을 찾으려고 노력 해요 :

/사용자/유진/라이브러리/개발자/CoreSimulator/디바이스/3C5E9A23-8220-4B37-BD14-F1E42EEC2C7C을 /data/Containers/Data/Application/20EBAAE2-6C6F-4651-A48F-16A222CCB3A2/Documents/asset.JPG

크립 틱뿐만 아니라하지만 존재하지 않는 이미지에 대한 실제 경로를 것 같다 ... 이미지 없음 그 길을 찾을 수 있습니다. 그리고 이것은 나를 아프게합니다.

처음부터 이미지를 저장해야합니까? 아니면 다른 방법이 있습니까?

AssetsLibrary API를 사용하여 여러 자습서를 살펴 보았지만 문제를 해결하는 데 도움이되지 않았습니다. 미리 감사드립니다.

답변

24

좋아요, 문제를 해결했습니다.

당신이해야 할 일은 단순히 이미지 (info[UIImagePickerControllerOriginalImage] as UIImage)를 잡고 주어진 디렉토리에 저장하기 만하면됩니다. 1 장의 그림 만 저장해야하는 경우 잘 작동합니다. 아래 코드 ID.

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) 

} 
+3

스위프트 2에 대한 답변을 업데이트 해 주실 수 있습니까? 고맙습니다! –

+5

스위프트 3에서 작동하지 않는다면 컴파일 할 수 있도록 코드를 변환했지만 리턴 된 경로가 선택된 이미지를 가리 키지 않습니다 – zumzum

+0

Swift 3의 경우이 해결책을 확인하십시오. http://stackoverflow.com/questions/4957972/iphone-uiimagepickercontroller -pave-image-to-app-folder/43456006 # 43456006 – XueYu

3
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { 
//this block of code grabs the path of the file 
let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL 
let imagePath = imageURL.path! 
let localPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(imagePath) 

//this block of code adds data to the above path 
let path = localPath.relativePath! 
let imageName = info[UIImagePickerControllerOriginalImage] as UIImage 
let data = UIImagePNGRepresentation(imageName) 
data?.writeToFile(imagePath, atomically: true) 

//this block grabs the NSURL so you can use it in CKASSET 
let photoURL = NSURL(fileURLWithPath: path) 
} 
+0

@Peter Kreinz, 이것이 도움이 되길 바랍니다. – DHuang

1

확인이 솔루션.

import AssetsLibrary 

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { 
      self.imagePicker = picker 
      if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { 
      let controller = CropViewController(image: selectedImage) 
      controller.delegate = self 
      picker.presentViewController(controller, animated: true, completion: nil) 
      } 

     else if let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL{ 
      let assetLibrary = ALAssetsLibrary() 
      assetLibrary.assetForURL(imageUrl , resultBlock: { (asset: ALAsset!) -> Void in 
      if let actualAsset = asset as ALAsset? { 
       let assetRep: ALAssetRepresentation = actualAsset.defaultRepresentation() 
       let iref = assetRep.fullResolutionImage().takeUnretainedValue() 
       let image = UIImage(CGImage: iref) 
       let controller = CropViewController(image: image) 
       controller.delegate = self 
       picker.presentViewController(controller, animated: true, completion: nil) 
      } 
      }, failureBlock: { (error) -> Void in 
      }) 
     } 
     } 
0

SWIFT 4에서 u는 제대로 작동하고,이를 시도 할 수 있습니다.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 


    if let imgUrl = info[UIImagePickerControllerImageURL] as? URL{ 
     let imgName = imgUrl.lastPathComponent 
     let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first 
     let localPath = documentDirectory?.appending(imgName) 

     let image = info[UIImagePickerControllerOriginalImage] as! UIImage 
     let data = UIImagePNGRepresentation(image)! as NSData 
     data.write(toFile: localPath!, atomically: true) 
     //let imageData = NSData(contentsOfFile: localPath!)! 
     let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!) 
     print(photoURL) 

    } 

    APPDEL.window?.rootViewController?.dismiss(animated: true, completion: nil) 
} 
관련 문제