[iOS] PHPickerViewController เครื่องมือสำหรับหยิบรูปจาก Photo Library ของใหม่บน iOS 14+

        PHPickerViewController เป็น class สำหรับเรียกใช้งาน Photo Library ซึ่งมีความสามารถเพิ่มเติมจาก UIImagePickerController ที่เป็นของเดิมที่น่าจะคุ้นเคยกันอยู่แล้ว

สิ่งที่เหนือกว่าของ PHPickerViewController

  • รองรับการเลือกหลายไฟล์ (Muli-selection)
  • รองรับ livePhoto 
  • เป็นการทำงานแบบ async
  • ไม่มีการขอ permission 

การใช้งานก็ไม่ได้ยุ่งยากมากมายไปกว่ากันซะเท่าไร

    import PhotosUI

ตั้งค่าและเรียกใช้งาน PHPickerViewController

    var configuration = PHPickerConfiguration()
    configuration.filter = .any(of: [.images, .livePhotos, .videos])
    configuration.selectionLimit = 2

    let picker = PHPickerViewController(configuration: configuration)
    picker.delegate = self
    self.present(picker, animated: true)


        และแน่นอนว่า การ handle response จำเป็นจะต้องใช้ delegate ตัวใหม่ เราจะต้อง implement protocol  PHPickerViewControllerDelegate ตัวใหม่ด้วย

    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        for result in results {
            let itemProvider = result.itemProvider
            if itemProvider.canLoadObject(ofClass: UIImage.self) {
                itemProvider.loadObject(ofClass: UIImage.self) { image, error in
                    DispatchQueue.main.async {
                        if let image = image as? UIImage {

                            //TODO: do something about image

                        }
                    }
                }
            }
        }
    }


        จากที่เล่าถึงข้อดีไปแล้วมาถึงข้อเสียกันบ้าง 

  • ❌ ยังไม่รองรับการเรียกใช้งานกล้อง ในขณะที่ UIImagePickerController ทำได้
  • ❌ ยังไม่รองรับ edit mode ในขณะที่ UIImagePickerController ทำได้


        สรุป ผมคิดว่า PHPickerViewController ยังไม่สามารถมาแทนที่ UIImagePickerController ได้ทั้งหมด นักพัฒนาต้องคิดถึงข้อดีข้อเสียเอง ซึ่งจากข้อดีข้อเสียคิดว่าอาจขึ้นอยู่กับการใช้งาน และการหยิบทั้ง 2 ตัวมาใช้ด้วยกันก็ไม่ได้เสียหายอะไร เพราะเป็น bundled library อยู่แล้วครับ

Facebook Comment

Recent Posts

Popular post of 7 days

[Java] ความแตกต่างระหว่าง Overloading กับ Overriding

Portal คืออะไรกันนะ???

Deeplink, Universal Links คืออะไร ทำงานร่วมกับ Mobile App ได้ยังไง

Popular

Portal คืออะไรกันนะ???

[Java] ความแตกต่างระหว่าง Overloading กับ Overriding

มาตรฐานการตั้งชื่อตัวแปร (Naming Convention)

Port Forwarding สำหรับคนใช้ AIS Fibre

เรื่องของ ++i กับ i++

Android Auto & Apple Carplay คืออะไร ใช้งานยังไง

Deeplink, Universal Links คืออะไร ทำงานร่วมกับ Mobile App ได้ยังไง

วิธีการสมัคร Apple Developer Program และ Enterprise Program ฉบับลงมือเอง

พิมพ์ซองจากรายชื่อ excel ด้วยวิธี Mail Merge

ทดสอบ Mobile App แบบ Automated ด้วย Appium ทำยังไงกันนะ