上传从图库中选择的图像进行解析

Uploading picked image from gallery to parse

所以我有这段编译无误的代码:

    @IBAction func btnImagePickerClicked(sender: AnyObject){
    let imagePicker = UIImagePickerController()

    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    imagePicker.mediaTypes = [kUTTypeImage as NSString]
    imagePicker.allowsEditing = false

    self.presentViewController(imagePicker, animated: true,
        completion: nil)
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        var user = PFUser.currentUser()
        let image = info[UIImagePickerControllerOriginalImage] as UIImage
        let imageData = UIImageJPEGRepresentation(image, 0.05)
        let imageFile = PFFile(name:"image.jpg", data:imageData)
        user["profilePicture"] = imageFile;
        user.saveInBackgroundWithBlock(nil)

        self.dismissViewControllerAnimated(true, completion: nil)
    }

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

但它会直接跳过 imagePickerController 函数,一旦我选择了一张图片,它就会将我发送回我的主 viewcontroller

您将委托设置为 self,因此您需要让这些方法可由 self 访问。 当它们嵌套在 IBAction 内部时,它们仅在其中可见。

采用委托方法并将它们放在 IBAction 之外。

@IBAction func btnImagePickerClicked(sender: AnyObject){
let imagePicker = UIImagePickerController()

imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = [kUTTypeImage as NSString]
imagePicker.allowsEditing = false

self.presentViewController(imagePicker, animated: true,
    completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    var user = PFUser.currentUser()
    let image = info[UIImagePickerControllerOriginalImage] as UIImage
    let imageData = UIImageJPEGRepresentation(image, 0.05)
    let imageFile = PFFile(name:"image.jpg", data:imageData)
    user["profilePicture"] = imageFile;
    user.saveInBackgroundWithBlock(nil)

    self.dismissViewControllerAnimated(true, completion: nil)
}

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

我已经测试过了,"didFinishPickingMediaWithInfo" 委托方法在选择图像后被调用。