iosswiftxcodephassetphfetchoptions

Swift - Initializer for conditional binding must have Optional type, not 'PHFetchResult<PHAsset>'


After updating the Xcode to 12.3, I'm getting the error "Initializer for conditional binding must have Optional type, not 'PHFetchResult'", its was working before as expected in previous versions.

func fetchRecentPhotos() {
    
    if !self.recentImagesArray.isEmpty{return}
    DispatchQueue.global(qos: .default).async {
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        
        if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions){
            if fetchResult.count > 0 {
                self.recentImagesArray.removeAll()
                for i in 0..<fetchResult.count {
                    let asset =  fetchResult.object(at: i)
                    self.recentImagesArray.append(RecentImage(asset: asset))
                }
                DispatchQueue.main.async {
                    if !self.isVideoStarted{
                        self.recentImagesCollectionView.reloadData()
                        self.recentMediaCollectionHeight.constant = 100
                        print("\(Date())fetchRecentPhotos ===== done")
                        if !self.isMultipleSelection{
                            self.setupGesturesForCameraSelection()
                        }
                        UIView.animate(withDuration: 0.2, animations: {
                            self.view.layoutIfNeeded()
                        })
                    }
                }
            }else{
                print("you got no photos")
            }
        }
    }
    }

is there anyone resolved the issue?

enter image description here


Solution

  • Please have a quick look at the documentation: fetchAssets returns a non-optional so you must not use if let.

    Replace

    if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions){ ... }
    

    with

    let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)