简体   繁体   中英

NSURL of an image from UIImagePicker

I am trying to upload an image from my phone to my Amazon S3 bucket:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!)
{
    var uploadReq = AWSS3TransferManagerUploadRequest()
    uploadReq.bucket = "bucketname";
    uploadReq.key = "testimage.png"
    uploadReq.body = image; //This line needs an NSURL
}

How can I get the NSURL of the image the user selected from a UIImagePickerController ?

While Zhengjie's answer might work. I found a more simple way to go about it:

    let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("imagetoupload"))
    let data = UIImagePNGRepresentation(image)
    data.writeToURL(fileURL!, atomically: true)
    uploadReq.body = fileURL

First U should save the Image to Document Directory. then Post the URL. U can do like this :

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
let data = UIImagePNGRepresentation(image)  // get the data
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true) as! [String]
let path = paths[0]
let fileName = "testimage.png"
let filePath = path.stringByAppendingPathComponent(fileName)  // get the file url to save 

var error:NSError?
if !data.writeToFile(photoPath, options: .DataWritingAtomic, error: &error) {// save the data
  logger.error("Error write file: \(error)")
}

upload.body = NSURL(string: filePath)  // used url to post to server
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM