Để chụp ảnh từ camera trong Swift, Apple khuyến khích dùng UIImagePickerController (đơn giản, chuẩn) thay vì AVFoundation (phức tạp, chỉ dùng khi cần tùy chỉnh sâu). Bài này demo chụp ảnh và hiển thị lên UIImageView.
Các bước
- Tạo project, thêm
UIImageViewvào Storyboard, kết nối outletimgView. - Class conform delegates:
UIImagePickerControllerDelegate, UINavigationControllerDelegate. - Thêm
NSCameraUsageDescriptionvào Info.plist. - Tap vào màn hình > mở camera > chụp > hiển thị ảnh.
Code hoàn chỉnh
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Tap gesture để mở camera
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(openCamera))
view.addGestureRecognizer(tapGesture)
}
@objc func openCamera() {
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
print("Camera không khả dụng (Simulator?)")
return
}
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .camera
picker.cameraDevice = .rear // hoặc .front
picker.allowsEditing = false
picker.showsCameraControls = true // Hiện UI mặc định (nút chụp, chuyển camera)
present(picker, animated: true)
}
// Delegate: User chụp xong ảnh
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let image = info[.originalImage] as? UIImage {
imgView.image = image
imgView.contentMode = .scaleAspectFit
}
picker.dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true)
}
}
Kết quả

Lưu ý quan trọng
- Không chạy trên Simulator (không có camera). Test trên thiết bị thật.
- Cần
NSCameraUsageDescriptiontrong Info.plist (iOS 10+). allowsEditing = truecho phép crop sau chụp – dùnginfo[.editedImage]thay vì.originalImage.- Để tùy chỉnh UI camera hoàn toàn (overlay, manual focus, RAW capture), dùng AVFoundation (
AVCaptureSession,AVCapturePhotoOutput).