PhotoKit

RSS for tag

Work with image and video assets managed by the Photos app, including those from iCloud Photos and Live Photos, using PhotoKit.

PhotoKit Documentation

Posts under PhotoKit tag

98 Posts
Sort by:
Post marked as solved
3 Replies
2.4k Views
Context: Using Xcode 13.2 and building on iOS 15.2 devices When installing the app for the 1st time on a device or simulator. Issue: When building and installing an app that requests access to the user’s Photo library, Xcode logs a  [GatekeeperXPC] Failed to open photo library error even before the app requests photo library access. Xcode Log example: 2021-12-16 18:33:57.848222+0100 App[20166:691616] [GatekeeperXPC] Failed to open photo library Error Domain=com.apple.photos.error Code=41011 "Unauthorized access: client does not have valid TCC authorization" UserInfo={NSLocalizedDescription=Unauthorized access: client does not have valid TCC authorization} 2021-12-16 18:33:57.848560+0100 App[20166:691616] [GatekeeperXPC] Got a bind failure for URL file:///Users/manuel/Library/Developer/CoreSimulator/Devices/F6302FEB-0448-4BAC-89A9-E34E8801B894/data/Media/, resetting bind state: <PLResult:0x600000cc5d40> failure: Error Domain=com.apple.photos.error Code=41011 "Unauthorized access: client does not have valid TCC authorization" UserInfo={NSLocalizedDescription=Unauthorized access: client does not have valid TCC authorization} (previous result: (null)) 2021-12-16 18:33:57.849131+0100 App[20166:691616] [GatekeeperXPC] XPC connection error to assetsd getLibraryServiceWithReply: : Error Domain=com.apple.photos.error Code=41011 "Unauthorized access: client does not have valid TCC authorization" UserInfo={NSLocalizedDescription=Unauthorized access: client does not have valid TCC authorization} 2021-12-16 18:33:57.849507+0100 App[20166:691616] [Backend] Swallowing proxy invocation: <NSInvocation: 0x6000019ede80> getLibraryServiceWithReply: CoreData: XPC:  Unable to create NSXPCConnection CoreData: fault: Something has gone badly awry initializing the XPC connection pool: *** -[__NSArrayM insertObject:atIndex:]: object cannot be nil 2021-12-16 18:33:57.855954+0100 App[20166:691616] CoreData: XPC: sendMessage: failed #0 After photo library access is granted, the Photos framework methods don't return any assets/albums etc. Nothing. Building for iOS 15.0 devices and Sims works fine. Anyone else seing this?
Posted
by manuelC.
Last updated
.
Post marked as solved
2 Replies
1.7k Views
Using Xcode 13 beta 4, I seem to have lost the ability to access user-created photo albums with PhotoKit (via PHAssetCollection.fetchAssetCollections). When I request albums of the type .smartAlbum, I get all the Smart Albums. However when I request .album, I get 0 results. Has anyone else run into this? Here's some example code: import SwiftUI import Photos struct ContentView: View { @State var status: PHAuthorizationStatus = PHPhotoLibrary .authorizationStatus(for: .readWrite) private static var collectionOptions: PHFetchOptions { let reverseChron = PHFetchOptions() reverseChron.sortDescriptors = [NSSortDescriptor(keyPath: \PHAssetCollection.endDate, ascending: false)] return reverseChron }     var body: some View { VStack { Text("Welcome!") .padding() if status == .authorized { Button("Load photos") { let userAlbums = PHAssetCollection.fetchAssetCollections( with: .album, subtype: .any, options: ContentView.collectionOptions ) print("List of albums:") for i in 0..<userAlbums.count { let album = userAlbums[i] print(album.localizedTitle ?? "[No title]") } } } }.onAppear() { PHPhotoLibrary.requestAuthorization(for: .readWrite) { aStatus in   status = aStatus   }   }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } } Edit: filed as FB9477907
Posted Last updated
.
Post not yet marked as solved
6 Replies
1.2k Views
We implemented the new PHPicker and have run into an issue we haven't been able to replicate on our own devices but see a lot of users running into it. The problem is an error after getting the PHPickerResults and trying to get the UIImages. Because the user can select several images at once, what we do is get the results and iterate over each itemProvider object. I'm following apple's guidance and checking if itemProvider canLoadObjectOfClass:UIImage.class, before executing itemProvider loadObjectOfClass:UIImage.class. However we are getting hundreds of reports of users where this last method returns an error. Firstly, this is how we configure our PHPickerViewController: PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init]; configuration.selectionLimit = self.pictureSelectionLimit; configuration.filter = PHPickerFilter.imagesFilter; configuration.preferredAssetRepresentationMode = PHPickerConfigurationAssetRepresentationModeCurrent; PHPickerViewController *pickerViewController = [[PHPickerViewController alloc] initWithConfiguration:configuration]; pickerViewController.delegate = self; pickerViewController.modalPresentationStyle = UIModalPresentationFullScreen; [viewController presentViewController:pickerViewController               animated:YES              completion:nil]; And this is what we do with the PHPickerResult. This is a method that returns a block with an array of an object NewPicture instantiated with the UIImage I should be getting. NSMutableArray *picArray = [[NSMutableArray alloc] init]; NSArray *itemProviders = [self.results custom_map: ^id _Nullable (PHPickerResult *_Nonnull current) {   return current.itemProvider; }]; dispatch_group_t dispatchGroup = dispatch_group_create(); for (NSItemProvider *itemProvider in itemProviders) { dispatch_group_enter(dispatchGroup); /**  We cannot properly retrieve raw type images with the current authorization status.  If the image is of type raw, we ignore it. */ if ([itemProvider hasItemConformingToTypeIdentifier:@"public.camera-raw-image"]) { NSException *exception = [NSException exceptionWithName:@"ImageIsTypeRaw"                         reason:[NSString stringWithFormat:@"Object is type raw. ItemProvider: %@", itemProvider.description]                        userInfo:nil]; // Log exception... dispatch_group_leave(dispatchGroup); continue; } if ([itemProvider canLoadObjectOfClass:UIImage.class]) { [itemProvider loadObjectOfClass:UIImage.class completionHandler: ^(__kindof id NSItemProviderReading _Nullable object, NSError *_Nullable error) {   if ([object isKindOfClass:UIImage.class]) { NewPicture *picture = [[NewPicture alloc]initWithImage:object]; [picArray addObject:picture]; }   if (error) { NSException *exception = [NSException exceptionWithName:@"CouldNotLoadImage"                         reason:[NSString stringWithFormat:@"Object is nil. UserInfo: %@", error.userInfo]                        userInfo:error.userInfo]; // Log exception... }   dispatch_group_leave(dispatchGroup); }]; } } dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{ picturesBlock(picArray); }); The most common error we see our users are getting is: Object is nil. UserInfo: { NSLocalizedDescription = "Cannot load representation of type public.jpeg"; NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=260 \"The file \U201cversion=1&amp;uuid=*&amp;mode=current.jpeg\U201d couldn\U2019t be opened because there is no such file.\" UserInfo={NSURL=file:///private/var/mobile/Containers/Shared/AppGroup/*/File%20Provider%20Storage/photospicker/version=1&amp;uuid=*&amp;mode=current.jpeg, NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/*/File Provider Storage/photospicker/version=1&amp;uuid=***&amp;mode=current.jpeg, NSUnderlyingError=0x283822970 {Error Domain=NSPOSIXErrorDomain Code=2 \"No such file or directory\"}}"; } I'm having a really hard time understanding why this sometimes fails. I'd really appreciate it if someone could give me a hand with this. I'm attaching the stack trace: stack_trace - https://developer.apple.com/forums/content/attachment/051f7018-05ff-4ad1-a626-29f248d0b497
Posted Last updated
.
Post not yet marked as solved
1 Replies
453 Views
My recording was stopped due to low battery and phone shutdown. When I reopen my app, the recorded ".mov video"(around 8GB) file is not moving/copying to PHPhotoLibrary and it shows internalError which is hard to understand the exact reason for denying to add the video file to PHPhotoLibrary. Error Domain=PHPhotosErrorDomain Code=-1 \"(null)\") So How to resolve such kind of internalError while adding assets to PHPhotoLibrary? Thanks & Regards, Natarajan S
Posted Last updated
.
Post marked as solved
1 Replies
529 Views
For PHPickerViewController, we know we can perform simple filtering by var config = PHPickerConfiguration() config.filter = PHPickerFilter.images But, how about we only want to show images with format JPG & PNG, but excluding GIF? This is because our app doesn't support GIF. Is it possible to do so?
Posted
by yccheok.
Last updated
.
Post marked as solved
2 Replies
199 Views
PHPickerViewController crashes with the error 'Picker's configuration is not a valid configuration.' when I try to use PHPickerViewController with a configuration that has preselectedAssetIdentifiers specified, and I can't figure out why. The identifier looks like "12345678-1234-1234-123456789012/L0/001", and I'm getting it from PHPickerResult.assetIdentifier. The exact same code works if I specify preselectedAssetIdentifiers as an empty array. I was worried that it was just undocumented that this feature required full photo library permissions, but after giving .readWrite permissions I still experience the issue. My iPhone 13 Pro is running 15.4.1. The only lead on this I've found is https://stackoverflow.com/questions/71765492/pickers-configuration-is-not-a-valid-configuration-swift, but I'm uncomfortable with the solution of recreating my project without identifying a cause that I can avoid in the future.
Posted
by nicksloan.
Last updated
.
Post not yet marked as solved
0 Replies
134 Views
Is there a way to update the metadata of a AVAsset/PHAsset to show a different still photo when the asset is not being played? If so what class should I look at to update the AVAsset or PHAsset? I am looking to edit the asset itself, not show a layer over the video. I would prefer to do this without trimming the video.
Posted Last updated
.
Post not yet marked as solved
11 Replies
2.3k Views
What is Error Domain=com.apple.photos.error Code=46104 mean? This error appears when I try to create an album on iOS14. case: User first gives AddOnly authorization and then gives ReadWrite authorization. After I get the ReadWrite authorization, create an album. code reference: [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{     PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName]  albumPlaceholder = [request placeholderForCreatedAssetCollection]; } completionHandler:^(BOOL success, NSError * _Nullable error) { // success is NO, error is "Error Domain=com.apple.photos.error Code=46104"  }]; The supplementary log information for the above question is as follows: 2020-08-17 11:28:19.470871+0800 XXXX[4255:1139139] CoreData: XPC: Unable to connect to server with options { NSXPCStoreServerEndpointFactory = "<PLXPCPhotoLibraryStoreEndpointFactory: 0x280ce8760>"; skipModelCheck = 1;} 2020-08-17 11:28:19.479533+0800 XXXX[4255:1139139] CoreData: XPC: Unable to load metadata: Error Domain=NSCocoaErrorDomain Code=134060 "关键数据出错。" UserInfo={Problem=Unable to send to server; failed after 8 attempts.} 2020-08-17 11:28:19.483149+0800 XXXXX[4255:1139139] [error] error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134060) CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134060) CoreData: annotation: userInfo:CoreData: annotation: Problem : Unable to send to server; failed after 8 attempts. CoreData: annotation: storeType: NSXPCStoreCoreData: annotation: configuration: (null) CoreData: annotation: URL: file:///var/mobile/Media/PhotoData/Photos.sqlite CoreData: annotation: options: CoreData: annotation: NSXPCStoreServerEndpointFactory : <PLXPCPhotoLibraryStoreEndpointFactory: 0x280ce8760>CoreData: annotation: skipModelCheck : 1 2020-08-17 11:28:19.485049+0800 XXXXX[4255:1139139] [Generic] Failed to connect to XPC PhotoLibraryStore file:///var/mobile/Media/PhotoData/Photos.sqlite with options { NSXPCStoreServerEndpointFactory = "<PLXPCPhotoLibraryStoreEndpointFactory: 0x280ce8760>"; skipModelCheck = 1;}: Error Domain=NSCocoaErrorDomain Code=134060 "关键数据出错。" UserInfo={Problem=Unable to send to server; failed after 8 attempts.} 2020-08-17 11:28:19.485565+0800 XXXXX[4255:1139139] [Migration] Failed to configure PSC for library file:///var/mobile/Media/: Error Domain=NSCocoaErrorDomain Code=134060 "关键数据出错。" UserInfo={Problem=Unable to send to server; failed after 8 attempts.} 2020-08-17 11:28:19.485943+0800 XXXXX[4255:1139139] [LibraryBundle] Unable to create PLLibraryBundleLogInfo because PSC is nil There is another problem. When saving the video, if the AddOnly permission is taken first and then the ReadWrite permission is taken, the performChanges method will freeze for more than 10 seconds before calling the completionHandler. The following is the log information: [Generic] Failed to connect to XPC PhotoLibraryStore file:///var/mobile/Media/PhotoData/Photos.sqlite with options { NSXPCStoreServerEndpointFactory = "<PLXPCPhotoLibraryStoreEndpointFactory: 0x280700d00>"; These problems only occur during a cold launch when the AddOnly permission is taken first and then the ReadWrite permission is taken. Whether the app only takes the AddOnly permission, only takes the ReadWrite permission, or closes the app after authorization and reopens it will not happen.
Posted
by THUYu.
Last updated
.
Post not yet marked as solved
1 Replies
197 Views
There are list of frames displayed at the bottom of the screen when videos are played on Photos app in iPhone. Which API is used for this functionality in iOS photo app. Is it possible to check this ?
Posted
by Unique_23.
Last updated
.
Post not yet marked as solved
1 Replies
167 Views
There's only a single function under PHPickerViewControllerDelegate which is didFinishPicking according to the documentation. How do I implement dismiss for the Cancel button that comes along when tapping out with PHPickerViewController? Have no problem if continue using UIImagePickerControllerDelegate, as it comes with imagePickerControllerDidCancel . However, if I were to implement with the new PHPickerViewController that currently only have a single function, how to enable proper dismiss right on the click of Cancel button instead of just relying the swipe down to dismiss the screen. Kindly advise. Thanks.
Posted
by CloverSly.
Last updated
.
Post marked as solved
2 Replies
331 Views
Started working on a photo editing extension in Xcode. no matter what I do whenever I select my extension to edit a photo the app crashes with the following error. After finding the solution for hours only thing I got was to uninstall and restart the app, but that too didn’t work. The following is the screenshot of the error.
Posted Last updated
.
Post not yet marked as solved
0 Replies
198 Views
I would like to be able to select a photo in iOS using Swift from the Photos library using UIImagePicker and copy all the image (with modified Exif metadata) to a new photo which I save in Photos. If I use UIActivityViewController to choose the save option (from copy/save/assign to contact/print/add to shared album/save to file), the input image Exif metadata is not transferred when I create a new UIimage from the loaded image data with the modified metadata. How can get the image with modified Exif metadata attached to the saved photo?
Posted Last updated
.
Post not yet marked as solved
4 Replies
611 Views
Work well in iOS 15.0 but after upgrading to iOS 15.1, the codes can't get worked. _ = PHLivePhoto.request(withResourceFileURLs: [pairedVideoURL, pairedImageURL], placeholderImage: nil, targetSize: CGSize.zero, contentMode: PHImageContentMode.aspectFit, resultHandler: { (livePhoto: PHLivePhoto?, info: [AnyHashable : Any]) -> Void in if let isDegraded = info[PHLivePhotoInfoIsDegradedKey] as? Bool, isDegraded { return } DispatchQueue.main.async { completion(livePhoto, (pairedImageURL, pairedVideoURL)) } })
Posted
by tpian928.
Last updated
.
Post not yet marked as solved
1 Replies
192 Views
tl;dr; Is there a way to ensure that only "Never" and "Read and Write" appear under Settings -&gt; App Name -&gt; Photos on devices running iOS 14 or higher? The Issue: The enhanced image library access permissions incorporated as part of iOS 14 are creating problems with a custom image selection flow created for an app and I'm just curious if there is a way to eliminate the "Selected Photos" option from the app settings until the app can be fully updated to offer users the enhanced security. I've removed the "Select Photos..." option from the iOS permission alert viewcontroller for the Images Library by setting the value for the PHPhotoLibraryPreventAutomaticLimitedAccessAlert key to 'true' as recommended in the Apple documentation: https://developer.apple.com/documentation/photokit/phauthorizationstatus/limited However, if the device is running iOS 14 or higher, the option for "Selected Photos" is still available when I go to the App's settings in the device's Settings menu. If a user interacts with permissions at this level the app does not function properly. I was wondering if anyone has experienced this as well and possibly come up with an interim solution.
Posted
by bcwoodard.
Last updated
.
Post not yet marked as solved
0 Replies
202 Views
Am using a Supervised Device with 15.4 OS Scenario: I have tried to push the Restriction payload to Device , with value true for "allowOpenFromUnmanagedToManaged" key . case 1: When i try to open a photo from Photo Library and try to open in with any Managed App ,the suggestions for managed app is not listed there. (Working as Expected) My Problem is: case 2: But when i open the Managed App and Try to add a photo , It allows me to open the Photo Library ,from where i can add it. If Sharing data from unmanaged to managed app is restricted, then it shouldn't be added in case2 ,Right? FYI: The managed App i have used in Outlook App Can Anyone Help me this strange Behaviour? Thanks In Advance
Posted Last updated
.
Post not yet marked as solved
4 Replies
1.1k Views
I use the following code to parse Photo metadata and this works well. However, I am unable to pull the new iOS 14 "caption" from this metadata (it worked in early iOS 14 betas, but has since stopped working in the GM.) Does anyone know how I can get the caption data from a PHAsset? Thanks! Stephen         let options = PHContentEditingInputRequestOptions()         options.isNetworkAccessAllowed = true         asset.requestContentEditingInput(with: options, completionHandler: {(contentEditingInput, _) -> Void in             if let url = contentEditingInput?.fullSizeImageURL {                 let fullImage = CIImage(contentsOf: url)                                  // get all the metadata                 self.allPhotoMetadata = fullImage?.properties ?? [:]                                  // {TIFF}                 if let tiffDict = self.allPhotoMetadata["{TIFF}"] as? [String:Any] {                     if tiffDict["Make"] != nil {                         self.cameraData[cameraKeys.make] = tiffDict["Make"]                     }                     if tiffDict["Model"] != nil {                         self.cameraData[cameraKeys.model] = tiffDict["Model"]                     }                     if tiffDict["ImageDescription"] != nil {                         self.imageData[imageKeys.caption] = tiffDict["ImageDescription"]                     }                 }                                  // {IPTC}                 if let iptcDict = self.allPhotoMetadata["{IPTC}"] as? [String:Any] {                     // if we didn't find a caption in the TIFF dict, try to get it from IPTC data                     // first try, Caption/Abtract, then ArtworkContentDescription                     if self.imageData[imageKeys.caption] == nil {                         if iptcDict["Caption/Abstract"] != nil {                             self.imageData[imageKeys.caption] = iptcDict["ArtworkContentDescription"]                         } else if iptcDict["ArtworkContentDescription"] != nil {                             self.imageData[imageKeys.caption] = iptcDict["ArtworkContentDescription"]                         }                     }                 }             }         })     }
Posted
by sorth.
Last updated
.
Post marked as solved
2 Replies
1.4k Views
Hello, I'm currently stuck trying to load a Video - previously picked by an PHPicker. In the photos you can see the current Views. The Videoplayer View stays unresponsive but in the first frames when the picker disappears you can see the thumbnail and a play button. What am i doing wrong? Should i load the file differently? This is my Picker: struct VideoPicker: UIViewControllerRepresentable{     @Binding var videoURL:String? func makeUIViewController(context: Context) -> PHPickerViewController {         var config = PHPickerConfiguration()         config.filter = .videos         let picker = PHPickerViewController(configuration: config)         picker.delegate = context.coordinator         return picker     } func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {} func makeCoordinator() -> Coordinator {         Coordinator(self)     } class Coordinator:NSObject, PHPickerViewControllerDelegate{ let parent:VideoPicker init(_ parent: VideoPicker){ self.parent = parent } func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { picker.dismiss(animated: true) { // do something on dismiss }              guard let provider = results.first?.itemProvider else {return} provider.loadFileRepresentation(forTypeIdentifier: "public.movie") { url, error in guard let url = url else {return} self.parent.videoURL = url.absoluteString print(url) print(FileManager.default.fileExists(atPath: url.path)) } } } } I'm totally able to get the URL (local URL - e.g.: file:///private/var/mobile/Containers/Data/Application/22126131-CBF4-4CAF-B943-22540F1096E1/tmp/.com.apple.Foundation.NSItemProvider. ) But for the life of me - the VideoPlayer won't play it: struct VideoView:View{     @Binding var videoURL:String? @Binding var showVideoPicker:Bool     var body: some View{         if let videoURL = videoURL {             VideoPlayer(player: AVPlayer(url: URL(fileURLWithPath:videoURL)))  .frame(width: 100, height: 100, alignment: .center)  .clipShape(RoundedRectangle(cornerRadius: 16)) .onLongPressGesture{ generator.feedback.notificationOccurred(.success) showVideoPicker.toggle() } } else{     Text("...") } } } Maybe somebody can point me in the right direction because in every Tutorial everybody uses stuff that's bundled to play a video. I want to use Videos from the Photos APP (apple). The videoURL is a @State in my ContentView. It gets updated through the VideoPicker. Sorry for the formatting this is my first Post.
Posted
by brunzbus.
Last updated
.