記得要在info.plist 加入這兩個權限
http://www.techotopia.com/index.php/An_Example_Swift_iOS_8_iPhone_Camera_Application
ㄧ個imageview 和兩個 button
import UIKit
import AVFoundation
import MobileCoreServices
// 沒有加入 import MobileCoreServices, 就找不到 kUTTypeImage
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var newMedia: Bool?
@IBAction func takePhoto(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(
UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType =
UIImagePickerControllerSourceType.camera
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true,
completion: nil)
newMedia = true
}
}
@IBAction func selectPhoto(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(
UIImagePickerControllerSourceType.savedPhotosAlbum) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType =
UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true,
completion: nil)
newMedia = false
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
self.dismiss(animated: true, completion: nil)
if mediaType.isEqual(to: kUTTypeImage as String) {
let image = info[UIImagePickerControllerOriginalImage]
as! UIImage
imageView.image = image
if (newMedia == true) {
UIImageWriteToSavedPhotosAlbum(image, self,
#selector(ViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)
} else if mediaType.isEqual(to: kUTTypeMovie as String) {
// Code to support video here
}
}
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafeRawPointer) {
if error != nil {
let alert = UIAlertController(title: "Save Failed",
message: "Failed to save image",
preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK",
style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true,
completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
}
沒有留言:
張貼留言