Search code examples
iosswiftiphonedirectory

Getting Error when create app folder in Swift


I got problem with creating folder for PhotoLibrary. Does anyone know what is wrong there?

var albumPlaceholder:PHObjectPlaceholder!

//create the folder
NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName)
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
    let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName)
    albumPlaceholder = request.placeholderForCreatedAssetCollection

}, completionHandler: { (success: Bool, error: NSError!) in
    NSLog("Creation of folder -> %@", (success ? "Success" : "Error!"))
    self.albumFound = (success ? true : false)
    if success {
        let collection = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([albumPlaceholder.localIdentifier], options: nil)
        self.assetCollection = collection?.firstObject as PHAssetCollection
    }
})

This code all the time prints Error! on console. Thanks in advance!

[Update] My error is like this.

Creation of folder -> Error! ViewWillAppear Error Domain=NSCocoaErrorDomain Code=2047 "Photos Access not allowed (authorization status 0)" UserInfo=0x7fd1fb664cc0 {NSLocalizedDescription=Photos Access not allowed (authorization status 0)}


Solution

  • You don't have permission to access Photo Library. You need to request it first. So use the following code for that:

    PHPhotoLibrary.requestAuthorization{ status in
       switch status {
          case .authorized:
             // Permission Granted
             print("Write your code here")
          case .denied:
             // Permission Denied
             print("User denied")
          default:
             print("Restricted")
       }
    }
    

    For more info refer : requestAuthorization