iOS 10 app crashes when trying to save image to photo library

Charlotte1993 picture Charlotte1993 · Sep 28, 2016 · Viewed 8.7k times · Source

I'm trying to save an image to the photo library in Swift 3 (I'm working with Xcode 8).

ViewController Code:

func shareImage(image: UIImage) {
    let items = [image]

    var activityVC: UIActivityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
    let excludeActivities: [UIActivityType] = [UIActivityType.airDrop,
                                               UIActivityType.assignToContact,
                                               UIActivityType.addToReadingList,
                                               UIActivityType.copyToPasteboard]

    activityVC.excludedActivityTypes = excludeActivities

    self.present(activityVC, animated: true, completion: nil)
}

When I run the application, and click on the button to take the screenshot (converting it to image, ..., that's all working perfectly), the app asks for permission to access the photo library, I tap the "OK" button, and then the app crashes. The image is not saved in the photo library.

The only clue I get from Xcode is the following:

2016-09-28 11:24:27.216043 Ajax Kids[4143:1545362] [error] error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///var/mobile/Media/PhotoData/Photos.sqlite?readonly_shm=1 options:{
NSPersistentStoreFileProtectionKey = NSFileProtectionCompleteUntilFirstUserAuthentication;
NSReadOnlyPersistentStoreOption = 1;
NSSQLitePersistWALOption = 1;
NSSQLitePragmasOption =     {
    "journal_mode" = WAL;
};
} ... returned error Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={reason=Failed to access file: 1} with userInfo dictionary {
reason = "Failed to access file: 1";
}
2016-09-28 11:24:27.216433 Ajax Kids[4143:1545362] [Migration] Unexpected error opening persistent store <private>, cannot attempt migration <private>)
2016-09-28 11:24:27.216568 Ajax Kids[4143:1545362] [Migration] Failed to open store <private>.  Requires update via assetsd (256: <private>)

Does anyone have any idea how to fix this?

Thanks in advance!

UPDATE

Sharing the image on Social Media works fine, so the problem is specified to saving the image in the photo library.

Answer

Andrey Oshev picture Andrey Oshev · Sep 28, 2016

Add new records in your new InfoPlist.strings file.

<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME)</string>

UPD: iOS 11 key