要求用户使用swift2从照片库或相机中选择照片

时间:2016-04-25 08:20:12

标签: ios iphone ipad swift2 uiimagepickercontroller

我希望用户从他的照片库或相机中选择一张照片。我无法找到任何例子。我想用UIAlertView之类的东西提示用户。

我的代码适用于照片库。

@IBAction func selectLeftPhoto(sender: AnyObject) {

        flag = 1

        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self;
        myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

        self.presentViewController(myPickerController, animated: true, completion: nil)

    }

    @IBAction func selectRightButton(sender: AnyObject) {

        flag = 2

        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self;
        myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

        self.presentViewController(myPickerController, animated: true, completion: nil)

    }



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

        let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage

        if flag == 1 {
            leftImage.image = pickedImage
            let imageData = UIImageJPEGRepresentation(pickedImage!, 0.5)
            let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
            photo1 = base64String

        }else if flag == 2 {
            rightImage.image = pickedImage
            let imageData = UIImageJPEGRepresentation(pickedImage!, 0.5)
            let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
            photo2 = base64String
        }

        dismissViewControllerAnimated(true, completion: nil)



    }

我的用户界面:

enter image description here

我想提示用户在点击选择照片按钮后从照片库或照相机中进行选择。

2 个答案:

答案 0 :(得分:1)

/

答案 1 :(得分:1)

 let optionMenu = UIAlertController(title: nil, message: "Choose Option for Image", preferredStyle: .ActionSheet)

// 2
let cameraAction = UIAlertAction(title: "Camera", style: .Default, handler: {
  (alert: UIAlertAction!) -> Void in
 flag = 1

    let myPickerController = UIImagePickerController()
    myPickerController.delegate = self;
    myPickerController.sourceType = UIImagePickerControllerSourceType.Camera

    self.presentViewController(myPickerController, animated: true, completion: nil)
})
let photoGalleryAction = UIAlertAction(title: "Photo Li", style: .Default, handler: {
  (alert: UIAlertAction!) -> Void in

 flag = 2

    let myPickerController = UIImagePickerController()
    myPickerController.delegate = self;
    myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

    self.presentViewController(myPickerController, animated: true, completion: nil)


})

//
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
  (alert: UIAlertAction!) -> Void in
  println("Cancelled")
})