Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách tải video từ URL và lưu vào Photo Album bằng Swift

Để tải video từ URL và lưu vào thư viện ảnh (Photos) trên iOS, cần thực hiện các bước: cấu hình quyền, tải trên background thread, lưu file tạm, ghi vào Photos.

1. Cấu hình Info.plist

<key>NSPhotoLibraryUsageDescription</key>
<string>Ứng dụng cần quyền lưu video vào thư viện ảnh</string>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

2. Code tải và lưu video

func downloadVideo() {
    let sampleURL = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
    
    DispatchQueue.global(qos: .background).async {
        guard let url = URL(string: sampleURL),
              let urlData = try? Data(contentsOf: url) else {
            print("Không tải được video")
            return
        }
        
        // Lưu file tạm vào Document directory
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = "\(documentsPath)/video_\(Date().timeIntervalSince1970).mp4"
        let fileURL = URL(fileURLWithPath: filePath)
        
        do {
            try urlData.write(to: fileURL, options: .atomic)
            
            // Lưu vào Photos
            DispatchQueue.main.async {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL)
                }) { success, error in
                    if success {
                        print("Đã lưu video vào Photos thành công")
                    } else {
                        print("Lỗi lưu Photos: \(error?.localizedDescription ?? "")")
                    }
                }
            }
        } catch {
            print("Lỗi ghi file: \(error)")
        }
    }
}

3. Gọi trong viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    downloadVideo()
}

Lưu ý quan trọng

  • Cần import Photos framework: import Photos.
  • Luôn tải video trên background thread (DispatchQueue.global) để không block UI.
  • Dùng PHPhotoLibrary.shared().performChanges để ghi vào Photos – yêu cầu quyền user.
  • URL video demo: https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4.
  • Trong production: Dùng URLSession với delegate để theo dõi tiến độ tải (progress), hỗ trợ resume, cancel.

Kết quả: Không có UI hiển thị, chỉ log console. Video sẽ xuất hiện trong app Photos sau khi thành công.