[ios] PhotoKit을 사용하여 이미지 및 비디오를 다양한 형식으로 내보내는 방법

iOS 애플리케이션을 개발하다 보면 사용자가 앱 내에서 저장된 이미지나 비디오를 외부로 내보내기를 원하는 경우가 있습니다. PhotoKit은 iOS에서 사진 및 비디오 관리를 위한 프레임워크로, 사용자의 사진 라이브러리에 접근하고 조작할 수 있는 기능을 제공합니다. 이번 포스트에서는 PhotoKit을 사용하여 이미지와 비디오를 다양한 형식으로 내보내는 방법에 대해 알아보겠습니다.

이미지 내보내기

PhotoKit을 사용하여 앱 내의 이미지를 다양한 형식으로 내보내기 위해서는 다음과 같은 단계를 따릅니다.

1. 사진 라이브러리에서 이미지 가져오기

import Photos

// 이미지 가져오기
func fetchImage() {
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
    
    if let asset = fetchResult.firstObject {
        PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: nil) { (image, info) in
            // 이미지 가져온 후 처리
        }
    }
}

2. 이미지 내보내기

func exportImage(_ image: UIImage, toURL url: URL, completion: @escaping (Bool, Error?) -> Void) {
    guard let data = image.jpegData(compressionQuality: 1.0) else {
        completion(false, nil)
        return
    }
    do {
        try data.write(to: url)
        completion(true, nil)
    } catch {
        completion(false, error)
    }
}

3. 내보낸 이미지 공유하기

내보낸 이미지를 공유하려면 UIActivityViewController를 사용할 수 있습니다.

func shareImage(_ url: URL, presentingViewController: UIViewController) {
    let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = presentingViewController.view
    presentingViewController.present(activityViewController, animated: true, completion: nil)
}

비디오 내보내기

비디오를 내보내는 방법은 이미지와 유사하지만, 비디오 데이터를 처리하는 부분에서 차이가 있습니다.

1. 사진 라이브러리에서 비디오 가져오기

// 비디오 가져오기
func fetchVideo() {
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
    
    if let asset = fetchResult.firstObject {
        let options = PHVideoRequestOptions()
        options.version = .original
        PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { (avAsset, audioMix, info) in
            guard let urlAsset = avAsset as? AVURLAsset else { return }
            let videoURL = urlAsset.url
            // 비디오 가져온 후 처리
        }
    }
}

2. 비디오 내보내기

func exportVideo(_ url: URL, toURL destinationURL: URL, completion: @escaping (Bool, Error?) -> Void) {
    do {
        try FileManager.default.copyItem(at: url, to: destinationURL)
        completion(true, nil)
    } catch {
        completion(false, error)
    }
}

3. 내보낸 비디오 공유하기

비디오를 공유하는 방법은 이미지와 유사합니다. 내보낸 비디오 파일의 URL을 UIActivityViewController에 전달하여 공유합니다.

결론

PhotoKit을 사용하여 이미지 및 비디오를 내보내는 방법을 알아보았습니다. 이를 통해 사용자가 앱 내에서 촬영한 사진이나 동영상을 외부로 쉽게 공유할 수 있습니다. 이러한 기능을 통해 사용자 경험을 향상시키고 더 많은 기능을 제공할 수 있을 것입니다.

참고 문헌: Apple Developer Documentation - PhotoKit, Hacking with Swift - How to export to a URL with UIImageWriteToSaveToURL, Hacking with Swift - Read and write video in iOS - AVFoundation