简体   繁体   中英

NSRangeException with PHFetchResult

I am developing an iOS App that fetches videos from the Photo gallery and it always worked. I just tested the app on a different device (this is not the first on which I test) and it crashes while I use the retrieved data and I don't understand why...

Here is my code :

self.videosAssets = PHAsset.fetchAssetsWithMediaType(.Video, options: nil)

if self.videosAssets != nil {
    for i in 0..<self.videosAssets!.count {
        if let video = self.videosAssets!.objectAtIndex(i) as? PHAsset {
            self.videos.append(Video(asset: video))
        }
    }
}

It fetches 221 videos but it crashes when i == 59.

Here is the error I get :

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
self.videosAssets = PHAsset.fetchAssetsWithMediaType(.Video, options: nil)

if let videoAssets = self.videosAssets {
   videoAssets.forEach { video in 
      if video as? PHAsset { self.videos.append(Video(asset: video)) }
   }
}

After testing the Video constructor, it was the problem. For some reason, when I call let resources = PHAssetResource.assetResourcesForAsset(asset) , it returns me an empty array and this is where the app was crashing.

Sorry for this useless post, maybe it will help someone...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM