Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีดาวน์โหลดวิดีโอจาก URL และบันทึกลง Photo Album ใน Swift

ดาวน์โหลดวิดีโอจาก URL แล้วบันทึกลง Photos App ต้องจัดการ Background Task, Permissions, และ PHPhotoLibrary

ข้อกำหนด Info.plist

<key>NSPhotoLibraryUsageDescription</key>
<string>แอปต้องการบันทึกวิดีโอลงแกลเลอรี่</string>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

โค้ดดาวน์โหลดและบันทึก

func downloadAndSaveVideo(from urlString: String) {
    guard let url = URL(string: urlString) else { return }
    
    // ดาวน์โหลดใน Background
    URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
        guard let self = self,
              let data = data,
              error == nil else {
            print("Download error: \(error?.localizedDescription ?? "Unknown")")
            return
        }
        
        // เขียนไฟล์ชั่วคราว
        let tempURL = FileManager.default.temporaryDirectory
            .appendingPathComponent("video_\(Date().timeIntervalSince1970).mp4")
        
        do {
            try data.write(to: tempURL)
            
            // บันทึกลง Photo Library
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: tempURL)
            }) { success, error in
                DispatchQueue.main.async {
                    if success {
                        print("✅ บันทึกวิดีโอสำเร็จ")
                        // แสดง Alert สำเร็จ
                    } else {
                        print("❌ บันทึก失敗: \(error?.localizedDescription ?? "")")
                    }
                    // ลบไฟล์ Temp
                    try? FileManager.default.removeItem(at: tempURL)
                }
            }
        } catch {
            print("Write error: \(error)")
        }
    }.resume()
}

ใช้งาน

override func viewDidLoad() {
    super.viewDidLoad()
    let videoURL = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
    downloadAndSaveVideo(from: videoURL)
}

ปรับปรุงสำหรับ Production

  • เพิ่ม Progress Indicator (ใช้ URLSessionDownloadDelegate)
  • Resume Capability (รองรับหยุด/ต่อได้)
  • Background Download (ใช้ URLSessionConfiguration.background)
  • Error Handling เต็มรูปแบบ (Network, Disk Space, Permission)
  • ใช้ Library: Kingfisher, SDWebImage (รองรับ Video), Alamofire

หมายเหตุ

  • ต้องขอ Permission Photos ครั้งแรก
  • วิดีโอขนาดใหญ่ควรดาวน์โหลดแบบ Streaming/Chunk
  • ทดสอบบน Device จริง (Simulator บางรุ่นไม่รองรับ Video Save)