8

The code shown below is what i've tried already.What I wish to achieve is to fetch all the photos from the device.Currently only a few are being fetched.How to modify the code so as to load all the images from device?

let fetchOptions = PHFetchOptions()

let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Moment, subtype: .Any, options: fetchOptions)

if let first_Obj:AnyObject = collection.firstObject
{
    self.assetCollection = first_Obj as! PHAssetCollection
}
Lyndsey Scott
  • 37,080
  • 10
  • 92
  • 128
Vineeth Krishnan
  • 432
  • 2
  • 9
  • 20

2 Answers2

24

Updated David's answer for iOS 10+ & Swift 4.x/3.x:

Request permission from the device to access photos:

Add the following value to your info.plist

Privacy - Photo Library Usage Description

And provide a string that is shown to the user.

Request all images:

PHPhotoLibrary.requestAuthorization { status in
    switch status {
    case .authorized:
        let fetchOptions = PHFetchOptions()
        let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        print("Found \(allPhotos.count) assets")
    case .denied, .restricted:
        print("Not allowed")
    case .notDetermined:
        // Should not see this when requesting
        print("Not determined yet")
    }
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132
1

All photos is pretty easy, but you need to ensure that you're authorized first. Here's some simple code to demonstrate:

PHPhotoLibrary.requestAuthorization { (status) in
    switch status
    {
    case .Authorized:
        print("Good to proceed")
        let fetchOptions = PHFetchOptions()
        let allPhotos = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
        print("Found \(allPhotos.count) images")
    case .Denied, .Restricted:
        print("Not allowed")
    case .NotDetermined:
        print("Not determined yet")
    }
}

On my phone this returns 25750 items. On a fresh simulator, this should yield 5 images.

ColdFire
  • 6,764
  • 6
  • 35
  • 51
David S.
  • 6,567
  • 1
  • 25
  • 45
  • 1
    what is the type of allPhotos?? – Vineeth Krishnan Jun 28 '16 at 08:55
  • If you enter the code, and control-click on the fetchAssetsWithMediaType function, you will see that it is a PHFetchResult. https://developer.apple.com/library/ios/documentation/Photos/Reference/PHFetchResult_Class/index.html – David S. Jun 28 '16 at 12:47