这是一个选择图像并上传它的简单方法吗?

时间:2015-11-12 10:27:12

标签: swift2 ios9 alamofire

我打电话给所有快速的开发者。我在这个主题的最后3天挣扎。有没有办法从图像选择器(iPhone的本地照片库)中选择图像并将其上传到服务器?我无法弄清楚如何做到这一点....只是吨过时的代码或没什么。

1 个答案:

答案 0 :(得分:0)

You should try to use a UIImagePickerController like this

@IBAction func takePhoto(sender: UIButton) {

    let picker = UIImagePickerController()
    picker.delegate = self;
    picker.allowsEditing = true;
    picker.sourceType = .PhotoLibrary;

    self.presentViewController(picker animated:true completion:nil); 
}

Then you can get the image in imagePickerController(_:didFinishPickingMediaWithInfo:) method from UIImagePickerControllerDelegate

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage
    UploadImage(chosenImage)

    picker.dismissViewControllerAnimated(true, completion: nil);
}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    picker.dismissViewControllerAnimated(true, completion: nil);
}

Finally you upload the image. Example using HTTP POST Check this answer

function UploadImage(image : UIImage) {
    var imageData = UIImagePNGRepresentation(image)
    if imageData == nil {
        print("image not valid")
        return
    }

    // Upload
    ....
}

Note This answer is directly written in the reply, please change any invalid code.