Capture photos, access library, and edit images with PhotoKit.
PhotoKit Overview
# Framework: PhotoKit
# Import: import Photos, import PhotosUI
# Permissions: NSPhotoLibraryUsageDescription, NSCameraUsageDescriptionPermissions
<!-- Info.plist -->
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to your photo library to select images</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs permission to save photos to your library</string>
<key>NSCameraUsageDescription</key>
<string>This app needs camera access to take photos</string>import Photos
class PhotoPermissionManager {
static func requestLibraryPermission() async -> PHAuthorizationStatus {
let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
switch status {
case .notDetermined:
return await withCheckedContinuation { continuation in
PHPhotoLibrary.requestAuthorization(for: .readWrite) { newStatus in
continuation.resume(returning: newStatus)
}
}
case .authorized, .limited:
return status
case .denied, .restricted:
return status
@unknown default:
return .denied
}
}
static func requestCameraPermission() async -> AVAuthorizationStatus {
let status = AVCaptureDevice.authorizationStatus(for: .video)
switch status {
case .notDetermined:
return await withCheckedContinuation { continuation in
AVCaptureDevice.requestAccess(for: .video) { granted in
continuation.resume(returning: granted ? .authorized : .denied)
}
}
default:
return status
}
}
}PHPickerViewController (Modern Picker)
import PhotosUI
import SwiftUI
// SwiftUI wrapper
struct PhotoPicker: UIViewControllerRepresentable {
@Binding var selectedImages: [UIImage]
let selectionLimit: Int
let filter: PHPickerFilter
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration()
config.filter = filter
config.selectionLimit = selectionLimit
config.preferredAssetRepresentationMode = .current
let picker = PHPickerViewController(configuration: config)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, PHPickerViewControllerDelegate {
let parent: PhotoPicker
init(_ parent: PhotoPicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
for result in results {
if result.itemProvider.canLoadObject(ofClass: UIImage.self) {
result.itemProvider.loadObject(ofClass: UIImage.self) { image, error in
if let image = image as? UIImage {
DispatchQueue.main.async {
self.parent.selectedImages.append(image)
}
}
}
}
}
}
}
}
// Usage
struct ContentView: View {
@State private var images: [UIImage] = []
var body: some View {
VStack {
ScrollView(.horizontal) {
HStack {
ForEach(images, id: \.self) { image in
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipShape(RoundedRectangle(cornerRadius: 10))
}
}
}
Button("Select Photos") {
// Present picker
}
.sheet(isPresented: .constant(false)) {
PhotoPicker(selectedImages: $images, selectionLimit: 5, filter: .images)
}
}
}
}PHPhotoLibrary (Direct Access)
// Fetch assets
func fetchRecentPhotos(limit: Int = 20) async -> [PHAsset] {
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
options.fetchLimit = limit
let result = PHAsset.fetchAssets(with: .image, options: options)
var assets: [PHAsset] = []
result.enumerateObjects { asset, _, _ in
assets.append(asset)
}
return assets
}
// Fetch albums
func fetchAlbums() -> [PHAssetCollection] {
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "estimatedAssetCount > 0")
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: options)
let userAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: options)
var albums: [PHAssetCollection] = []
smartAlbums.enumerateObjects { collection, _, _ in albums.append(collection) }
userAlbums.enumerateObjects { collection, _, _ in albums.append(collection) }
return albums
}
// Get image from asset
func requestImage(for asset: PHAsset, targetSize: CGSize = PHImageManagerMaximumSize) async -> UIImage? {
await withCheckedContinuation { continuation in
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.resizeMode = .exact
PHImageManager.default().requestImage(
for: asset,
targetSize: targetSize,
contentMode: .aspectFill,
options: options
) { image, _ in
continuation.resume(returning: image)
}
}
}
// Get full resolution image data
func requestImageData(for asset: PHAsset) async -> Data? {
await withCheckedContinuation { continuation in
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.version = .current
PHImageManager.default().requestImageDataAndOrientation(
for: asset,
options: options
) { data, _, _, _ in
continuation.resume(returning: data)
}
}
}Saving Photos
// Save UIImage to library
func saveImage(_ image: UIImage) async throws {
try await PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.creationRequestForAsset(from: image)
}
}
// Save image data
func saveImageData(_ data: Data) async throws {
try await PHPhotoLibrary.shared().performChanges {
let request = PHAssetCreationRequest.forAsset()
request.addResource(with: .photo, data: data, options: nil)
}
}
// Save to specific album
func saveToAlbum(_ image: UIImage, albumName: String) async throws {
// Find or create album
let album = try await findOrCreateAlbum(named: albumName)
try await PHPhotoLibrary.shared().performChanges {
let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceholder = assetRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: album)
albumChangeRequest?.addAssets([assetPlaceholder!] as NSArray)
}
}
func findOrCreateAlbum(named name: String) async throws -> PHAssetCollection {
// Check existing
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", name)
let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let album = collections.firstObject {
return album
}
// Create new
var albumPlaceholder: PHObjectPlaceholder!
try await PHPhotoLibrary.shared().performChanges {
let createRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
albumPlaceholder = createRequest.placeholderForCreatedAssetCollection
}
let fetchResult = PHAssetCollection.fetchAssetCollections(
withLocalIdentifiers: [albumPlaceholder.localIdentifier],
options: nil
)
guard let album = fetchResult.firstObject else {
throw NSError(domain: "PhotoKit", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to create album"])
}
return album
}Editing Images
// Edit asset metadata
func editAssetMetadata(_ asset: PHAsset, title: String?, location: CLLocation?) async throws {
try await PHPhotoLibrary.shared().performChanges {
let request = PHAssetChangeRequest(for: asset)
request.title = title
request.location = location
}
}
// Content editing (filters, adjustments)
func editAssetContent(_ asset: PHAsset, filter: CIFilter) async throws {
guard let inputImage = await requestFullImage(for: asset) else { return }
let outputImage = filter.outputImage!
let context = CIContext()
guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return }
let editedImage = UIImage(cgImage: cgImage)
try await PHPhotoLibrary.shared().performChanges {
let request = PHAssetChangeRequest(for: asset)
request.contentEditingOutput = PHContentEditingOutput(asset: asset)
request.contentEditingOutput?.renderedContentURL = try saveEditedImage(editedImage)
}
}
func requestFullImage(for asset: PHAsset) async -> UIImage? {
await withCheckedContinuation { continuation in
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.version = .current
options.resizeMode = .none
PHImageManager.default().requestImage(
for: asset,
targetSize: PHImageManagerMaximumSize,
contentMode: .default,
options: options
) { image, _ in
continuation.resume(returning: image)
}
}
}
func saveEditedImage(_ image: UIImage) throws -> URL {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("edited_\(UUID().uuidString).jpg")
let data = image.jpegData(compressionQuality: 0.9)!
try data.write(to: url)
return url
}Live Photos & Videos
// Fetch Live Photos
func fetchLivePhotos() async -> [PHAsset] {
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "mediaSubtype == %d", PHAssetMediaSubtype.photoLive.rawValue)
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let result = PHAsset.fetchAssets(with: .image, options: options)
var assets: [PHAsset] = []
result.enumerateObjects { asset, _, _ in assets.append(asset) }
return assets
}
// Play Live Photo
func playLivePhoto(_ asset: PHAsset, in view: PHLivePhotoView) async {
let options = PHLivePhotoRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
await withCheckedContinuation { continuation in
PHImageManager.default().requestLivePhoto(
for: asset,
targetSize: view.bounds.size,
contentMode: .aspectFit,
options: options
) { livePhoto, _ in
view.livePhoto = livePhoto
continuation.resume()
}
}
}
// Fetch Videos
func fetchVideos() async -> [PHAsset] {
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let result = PHAsset.fetchAssets(with: .video, options: options)
var assets: [PHAsset] = []
result.enumerateObjects { asset, _, _ in assets.append(asset) }
return assets
}
// Export video
func exportVideo(_ asset: PHAsset, to url: URL) async throws {
let options = PHVideoRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { avAsset, _, _ in
guard let avAsset = avAsset else {
continuation.resume(throwing: NSError(domain: "PhotoKit", code: -1))
return
}
guard let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetHighestQuality) else {
continuation.resume(throwing: NSError(domain: "PhotoKit", code: -2))
return
}
exportSession.outputURL = url
exportSession.outputFileType = .mp4
exportSession.exportAsynchronously {
switch exportSession.status {
case .completed:
continuation.resume()
case .failed:
continuation.resume(throwing: exportSession.error!)
case .cancelled:
continuation.resume(throwing: CancellationError())
default:
continuation.resume(throwing: NSError(domain: "PhotoKit", code: -3))
}
}
}
}
}AVCaptureSession (Custom Camera)
import AVFoundation
class CameraSession: NSObject, ObservableObject {
let session = AVCaptureSession()
private let photoOutput = AVCapturePhotoOutput()
private var continuation: CheckedContinuation<UIImage, Error>?
override init() {
super.init()
setupSession()
}
private func setupSession() {
session.beginConfiguration()
session.sessionPreset = .photo
// Add video input
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
let input = try? AVCaptureDeviceInput(device: device),
session.canAddInput(input) else { return }
session.addInput(input)
// Add photo output
if session.canAddOutput(photoOutput) {
session.addOutput(photoOutput)
photoOutput.isHighResolutionCaptureEnabled = true
photoOutput.maxPhotoQualityPrioritization = .quality
}
session.commitConfiguration()
}
func start() {
DispatchQueue.global(qos: .userInitiated).async {
self.session.startRunning()
}
}
func stop() {
session.stopRunning()
}
func capturePhoto() async throws -> UIImage {
try await withCheckedThrowingContinuation { continuation in
self.continuation = continuation
let settings = AVCapturePhotoSettings()
settings.flashMode = .auto
photoOutput.capturePhoto(with: settings, delegate: self)
}
}
func switchCamera() {
session.beginConfiguration()
// Remove existing input
if let currentInput = session.inputs.first as? AVCaptureDeviceInput {
session.removeInput(currentInput)
let newPosition: AVCaptureDevice.Position = currentInput.device.position == .back ? .front : .back
guard let newDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: newPosition),
let newInput = try? AVCaptureDeviceInput(device: newDevice),
session.canAddInput(newInput) else { return }
session.addInput(newInput)
}
session.commitConfiguration()
}
}
extension CameraSession: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let error = error {
continuation?.resume(throwing: error)
return
}
guard let data = photo.fileDataRepresentation(),
let image = UIImage(data: data) else {
continuation?.resume(throwing: NSError(domain: "Camera", code: -1))
return
}
continuation?.resume(returning: image)
continuation = nil
}
}SwiftUI Camera Preview
struct CameraPreview: UIViewRepresentable {
let session: AVCaptureSession
func makeUIView(context: Context) -> PreviewView {
let view = PreviewView()
view.videoPreviewLayer.session = session
view.videoPreviewLayer.videoGravity = .resizeAspectFill
return view
}
func updateUIView(_ uiView: PreviewView, context: Context) {}
}
class PreviewView: UIView {
override class var layerClass: AnyClass {
AVCaptureVideoPreviewLayer.self
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
layer as! AVCaptureVideoPreviewLayer
}
}
// Usage
struct CameraView: View {
@StateObject private var camera = CameraSession()
@State private var capturedImage: UIImage?
var body: some View {
ZStack {
CameraPreview(session: camera.session)
.ignoresSafeArea()
VStack {
Spacer()
HStack {
Button(action: { camera.switchCamera() }) {
Image(systemName: "camera.rotate")
.font(.title)
.foregroundColor(.white)
.padding()
}
Spacer()
Button(action: capturePhoto) {
Circle()
.fill(Color.white)
.frame(width: 70, height: 70)
.overlay(Circle().stroke(Color.gray, lineWidth: 3))
}
Spacer()
Button(action: { /* flash */ }) {
Image(systemName: "bolt.fill")
.font(.title)
.foregroundColor(.white)
.padding()
}
}
.padding(.bottom, 30)
}
}
.onAppear { camera.start() }
.onDisappear { camera.stop() }
.sheet(item: $capturedImage) { image in
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
}
}
func capturePhoto() {
Task {
do {
let image = try await camera.capturePhoto()
capturedImage = image
} catch {
print("Capture error: \(error)")
}
}
}
}Try It
Request permissions. Use PHPickerViewController. Fetch assets. Save to library. Build custom camera with AVCaptureSession.
# Add permissions to Info.plist
# Import Photos, PhotosUI, AVFoundationPhoto & Camera features
- Build photo picker with PHPickerViewController
- Create album and save photos
- Implement custom camera with AVCaptureSession
- Add photo editing with filters
- Handle Live Photos and videos
- Test on device (simulator has limited camera)
Use PHPickerViewController for modern picking (no permission needed for selection). PHPhotoLibrary for direct access and saving. AVCaptureSession for custom camera UI. Request permissions before access. Save to albums for organization.