When using PhotosPicker in SwiftUI to let users pick a photo, it will fail to load after switching to the "Collections" tab on iOS 18. This issue doesn't occur on iOS 17. Additionally, using PHPickerViewController will still have the same issue.
The code is pretty simple:
struct ContentView: View {
@State private var selection: PhotosPickerItem? = nil
var body: some View {
VStack {
PhotosPicker("Pick photo", selection: $selection)
}
.padding()
}
}
And I create a repo for this code: https://github.com/JuniperPhoton/PhotosPickerIssueiOS18
This issue has been reported via Feedback app, and the report ID is FB15069998.
I tested in the Xcode 16 Beta 6 and iOS 18 Beta 8. However with the Xcode 16 RC and the iOS 18 RC, this issue still exists.
Hoping to find out any workaround to resolve this issue. Thanks.
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
PhotoKit
RSS for tagWork with image and video assets managed by the Photos app, including those from iCloud Photos and Live Photos, using PhotoKit.
Posts under PhotoKit tag
78 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I am trying to retrieve all PHAssets from the Photos Library that have been edited. PHAsset contains the "hasAdjustments" boolean variable but I cannot use that in an NSPredicate to filter for edited photos.
What is the proper mechanism to filter out non-edited photos?
Here is the code I have written that crashes:
let formatString = "mediaType = %d && hasAdjustments == YES"
let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
allPhotosOptions.predicate = NSPredicate(format: formatString, PHAssetMediaType.image.rawValue)
allPhotosOptions.includeAssetSourceTypes = [.typeUserLibrary, .typeiTunesSynced, .typeCloudShared]
return PHAsset.fetchAssets(with: allPhotosOptions)
Thanks,
Rick
I have an Electron app built for macOS, and it was distributed via 'Developer ID' for years, it worked well and I was able to access the photos in the system Photos library. Surely I already have the 'NSPhotoLibraryUsageDescription' key in Info.plist.
Recently we are trying to publish this app to Mac App Store, so I have to turn on the sandbox, after that the app starts giving XPC errors while accessing the Photos library. The errors look like:
PHAuthorizationStatus: Authorized
CoreData: XPC: sendMessage: failed #0
CoreData: XPC: Unable to sendMessage: to server
...
CoreData: XPC: sendMessage: failed #7
CoreData: XPC: Unable to connect to server with options {
NSPersistentHistoryTrackingKey = 1;
NSXPCStoreServerEndpointFactory = "<PLXPCPhotoLibraryStoreEndpointFactory: 0x7fc67e8af370>";
skipModelCheck = 1;
}
CoreData: XPC: Unable to load metadata: Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={Problem=Unable to send to server; failed after 8 attempts.}
CoreData: fault: Unable to create token NSXPCConnection. NSXPCStoreServerEndpointFactory 0x7fc67e8af370 -newEndpoint returned nil
CoreData: error: Failed to create NSXPCConnection
It seems the app could detect the current PHAuthorizationStatus which is Authorized, but it can't fetch the photos from the Photos library (using PhotoKit).
I learned from here that I could look for errors from the sandboxd daemon, so I did that, here is what I saw:
Sandbox: Picture Keeper(32625) deny(1) mach-lookup com.apple.photos.service
Violation: deny(1) mach-lookup com.apple.photos.service
Process: Picture Keeper [32625]
Path: /Applications/Picture Keeper.app/Contents/MacOS/Picture Keeper
Load Address: 0x103bd3000
Identifier: com.simplifieditproducts.picturekeepermas
Version: 4575 (4.5.75)
Code Type: x86_64 (Native)
Parent Process: Picture Keeper [1]
Responsible: /Applications/Picture Keeper.app/Contents/MacOS/Picture Keeper
User ID: 501
Date/Time: 2024-08-26 16:16:14.645 EDT
OS Version: macOS 14.5 (23F79)
Release Type: User
Report Version: 8
MetaData: {"process_path":["Users","Kevin","Projects","Electron","picturekeeper-electron","dist","picturekeeper","mas-dev","Picture Keeper.app","Contents","MacOS","Picture Keeper"],"apple-internal":false,"primary-filter":"global-name","policy-description":"Sandbox","flags":5,"platform-policy":false,"build":"macOS 14.5 (23F79)","process-path":"\/Applications\/Picture Keeper.app\/Contents\/MacOS\/Picture Keeper","responsible-process-path":"\/Applications\/Picture Keeper.app\/Contents\/MacOS\/Picture Keeper","primary-filter-value":"com.apple.photos.service","platform_binary":"no","responsible-process-signing-id":"com.simplifieditproducts.picturekeepermas","hardware":"Mac","target":"com.apple.photos.service","action":"deny","mach_namespace":1,"checker-pid":1,"container":"\/Users\/Kevin\/Library\/Containers\/com.simplifieditproducts.picturekeepermas\/Data","binary-in-trust-cache":false,"team-id":"LU744924UY","process":"Picture Keeper","global-name":"com.apple.photos.service","platform-binary":false,"pid":32625,"summary":"deny(1) mach-lookup com.apple.photos.service","checker":"launchd","responsible-process-team-id":"xxxxx","operation":"mach-lookup","normalized_target":["com.apple.photos.service"],"errno":1,"uid":501,"profile-flags":0,"profile-in-collection":false,"sandbox_checker":"launchd","signing-id":"com.simplifieditproducts.picturekeepermas","release-type":"User"}
I believe I already have the necessary entitlements for the Photos library, see:
codesign -d --entitlements - /Applications/Picture\ Keeper.app/Contents/MacOS/Picture\ Keeper
[Dict]
[Key] com.apple.application-identifier
[Value]
[String] xxxx.com.simplifieditproducts.picturekeepermas
[Key] com.apple.developer.team-identifier
[Value]
[String] xxxx
[Key] com.apple.security.app-sandbox
[Value]
[Bool] true
[Key] com.apple.security.application-groups
[Value]
[Array]
[String] xxxx.com.simplifieditproducts.picturekeepermas
[Key] com.apple.security.assets.movies.read-only
[Value]
[Bool] true
[Key] com.apple.security.assets.music.read-only
[Value]
[Bool] true
[Key] com.apple.security.assets.pictures.read-write
[Value]
[Bool] true
[Key] com.apple.security.cs.allow-dyld-environment-variables
[Value]
[Bool] true
[Key] com.apple.security.cs.allow-jit
[Value]
[Bool] true
[Key] com.apple.security.cs.allow-unsigned-executable-memory
[Value]
[Bool] true
[Key] com.apple.security.cs.disable-executable-page-protection
[Value]
[Bool] true
[Key] com.apple.security.cs.disable-library-validation
[Value]
[Bool] true
[Key] com.apple.security.device.usb
[Value]
[Bool] true
[Key] com.apple.security.files.bookmarks.app-scope
[Value]
[Bool] true
[Key] com.apple.security.files.bookmarks.document-scope
[Value]
[Bool] true
[Key] com.apple.security.files.downloads.read-only
[Value]
[Bool] true
[Key] com.apple.security.files.user-selected.read-write
[Value]
[Bool] true
[Key] com.apple.security.network.client
[Value]
[Bool] true
[Key] com.apple.security.network.server
[Value]
[Bool] true
[Key] com.apple.security.personal-information.location
[Value]
[Bool] true
[Key] com.apple.security.personal-information.photos-library
[Value]
[Bool] true
By the way, the Photos library related code was built into a .node file (which is a dylib), and it will be loaded by the main executable during runtime.
Anything I missed? Thank you!
I am using PHPickerViewController to get assets from the photo library. It works fine, but it presents the images so that the newest is first. I would like to choose the order. In some cases I prefer the oldest image to be first.
I have checked in PHPickerConfiguration with no success. I am just wondering if it is possible.
MacBook Air black screen
Dear Experts,
When I use PHImageManager's requestImageDataAndOrientationForAsset method I always seem to get JPEG data, even when the original items in the photo library are PNGs (such as screenshots) or HEICs.
Have I missed a setting somewhere that determines whether or not a "most compatible" format is used in this API?
Thanks.
I have the Facebook SDK version 17.0.2 and xcode 15. Sharing photos and links work fine but when I try sharing videos, I get the following error:
Failed to log access with error: access=<PATCCAccess 0x301d12b20> accessor:<<PAApplication 0x301d27e30 identifierType:auditToken identifier:{pid:18440, version:47210}>> identifier:A9159DCD-76B1-4C77-A01E-DA611929B50B kind:intervalEvent timestampAdjustment:0 visibilityState:0 assetIdentifierCount:0 accessCount:0 tccService:kTCCServicePhotos, error=Error Domain=NSCocoaErrorDomain Code=4097 "connection to service with pid 15679 named com.apple.privacyaccountingd" UserInfo={NSDebugDescription=connection to service with pid 15679 named com.apple.privacyaccountingd}
Hi, I notice a very slow transfer rate when I try to transfer a file picked via .photosPicker. This happens especially when I try to import a 4k/60fps video.
SwiftUI:
VStack {
Button("Pick a video") {
model.isPhotoPickerView = true
}
.photosPicker(isPresented: $model.isPhotoPickerView, selection: $model.selectedImageList, maxSelectionCount: 1, matching: .videos)
.onChange(of: model.selectedImageList, { old, new in
model.handlePhotoPicker()
})
}
View Model to handle Photo Picker action:
private class PageModel: ObservableObject {
//other methods
@MainActor
public func handlePhotoPicker() {
if selectedImageList.isEmpty {
return
}
guard let item = selectedImageList.first else {
return
}
Task {
do {
if let video = try await item.loadTransferable(type: VideoTransferable.self) {
let file = video.url
//video url arrived
}
} catch {
//handle error
}
}
}
}
Now the VideoTransferable :
struct VideoTransferable: Transferable {
let url: URL
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(contentType: .movie) { video in
SentTransferredFile(video.url)
}
importing: { received in
//takes too much time to import large 4K video recorded from iPhone's main camera
let copy = FileManager.documentsDirectory.appendingPathComponent(FolderType.temp.rawValue).appendingPathComponent("video_\(Int64(Date().timeIntervalSince1970 * 1000)).MOV")
if FileManager.default.fileExists(atPath: copy.path) {
try FileManager.default.removeItem(at: copy)
}
try FileManager.default.copyItem(at: received.file, to: copy)
return Self.init(url: copy)
}
}
}
To my surprise this issue doesn't happen when I use a custom UIViewControllerRepresentable to wrap UIImagePickerController() and setting videoExportPreset property of the picker to AVAssetExportPresetPassthrough
Can someone point me out where I am wrong?
Hi! I am having a bit of trouble with the Photos Picker. In my app, users are able to select photos to appear in a grid, right in the app. I am using the new Photos Picker with SwiftUI. I want to be able to have my users select the images after they have been added to the View. So I want there to be a select button in the top toolbar on the leading side, and then once the user hits the select button, they can select the photos they want to remove on the grid, just like in the photos app, and then where the button to add photos originally is, there will be a trash icon to remove the selected photos from the grid.
How would I do this? I have attached my code below for my view, as well as my PhotoPicker:
import PhotosUI
struct LifestyleImagePicker: View {
@StateObject var imagePicker = ImagePicker()
@State private var showingDetail = false
@State private var selectedIndex = 0
@State private var isSelecting = false
@State private var isAddingPhoto = false
let columns = [GridItem(.adaptive(minimum: 100))]
var body: some View {
NavigationSplitView {
VStack {
if !imagePicker.images.isEmpty {
ScrollView {
LazyVGrid(columns: columns, spacing: 3) {
ForEach(imagePicker.images.indices, id: \.self) { index in
imagePicker.images[index]
.resizable()
.scaledToFit()
.onTapGesture {
selectedIndex = index
showingDetail = true
}
}
}
}
} else {
Text("Tap the plus icon to add photos to your own Inspo Board.")
.multilineTextAlignment(.center)
}
}
.padding()
.navigationTitle("Lifestyle")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
PhotosPicker(selection: $imagePicker.imageSelections,
maxSelectionCount: 10,
matching: .images,
photoLibrary: .shared()) {
Image(systemName: "photo.badge.plus")
.imageScale(.large)
}
}
}
} detail: {
Text("Pick your lifestyle")
}
.sheet(isPresented: $showingDetail) {
DetailImageView(images: $imagePicker.images, selectedIndex: selectedIndex)
}
}
}
#Preview {
LifestyleImagePicker()
}
import PhotosUI
import Combine
import Foundation
@MainActor
class ImagePicker: ObservableObject {
@Published var image: Image?
@Published var images: [Image] = []
@Published var imageSelection: PhotosPickerItem? {
didSet {
if let imageSelection {
Task {
try await loadTransferable(from: imageSelection)
}
}
}
}
@Published var imageSelections: [PhotosPickerItem] = [] {
didSet {
Task {
if !imageSelections.isEmpty {
try await loadTransferable(from: imageSelections)
imageSelections = []
}
}
}
}
func loadTransferable(from imageSelections: [PhotosPickerItem]) async throws {
do {
for imageSelection in imageSelections {
if let data = try await imageSelection.loadTransferable(type: Data.self) {
if let uiImage = UIImage(data: data) {
self.images.append(Image(uiImage: uiImage))
}
}
}
} catch {
print(error.localizedDescription)
}
}
func loadTransferable(from imageSelection: PhotosPickerItem?) async throws {
do {
if let data = try await imageSelection?.loadTransferable(type: Data.self) {
if let uiImage = UIImage(data: data) {
self.image = Image(uiImage: uiImage)
}
}
} catch {
print(error.localizedDescription)
image = nil
}
}
}
Dear Experts,
In "limited access" photos mode, I present a PHPickerViewController. It shows the entire photo library, with a note at the top saying that the app can only access the items that I select. I select a photo.
In the delegate method, I get a PHPickerResult containing a plausible-looking string for the assetIdentifier. It's the same string that I get for that photo in "full access" mode.
Should this photo now be accessible, or do I need to do something else at this point?
When I call fetchAssetsWithLocalIdentifiers using this assetIdentifier, I get no results. When I call cloudIdentifierMappingsForLocalIdentifiers, I get error PHPhotosErrorIdentifierNotFound. In "full access" mode, both work OK.
What am I missing?
Thanks.
Following Metadata should be accessible from PHAsset Object: Title, caption, Keywords. Write now they are available in the SQLite Photo Library, but thats is not a clean solution.
I have the following code:
extension AssetGridViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
Task { @MainActor in
guard let changes = changeInstance.changeDetails(for: fetchResult) else { return }
fetchResult = changes.fetchResultAfterChanges
}
}
}
With Swift 6, this generates a compilation error: Main actor-isolated instance method 'photoLibraryDidChange' cannot be used to satisfy nonisolated protocol requirement. The error includes to fix-it suggestions:
Adding nonisolated to the function (nonisolated func photoLibraryDidChange(_ changeInstance: PHChange))
Adding @preconcurrency to the protocol conformance (extension AssetGridViewController: @preconcurrency PHPhotoLibraryChangeObserver {)
Both options generate a runtime error: EXC_BREAKPOINT (code=1, subcode=0x105b7c400). For context, AssetGridViewController is a regular UIViewController.
Any ideas on how to fix this?
I've had an app that edits photos in your library since the PhotoKit API was released in iOS 8. I know it was required if you preserve photo metadata you had to change the value of Orientation to 1 (up), otherwise PhotoKit would fail to perform the asset change request. When I remove this code, I'm seeing Orientation is getting changed to 1 automatically both at root and in the TIFF dictionary (tested with iOS 18). I wanted to confirm this is expected behavior, the system does this for us now? If so, can I remove this code for iOS 15+, or was it a recent iOS version this started happening? Thanks!
Is it possible to sort the user library assets by date captured? The Photos app in iOS 18 lets you choose between Date Captured and Recently Added and I want to offer that same choice in my app. This seems to always sort them by creation date (which I believe is the same as recently added):
let assetCollection = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).firstObject!
let fetchResult = PHAsset.fetchAssets(in: assetCollection, options: PHFetchOptions.imageMediaType())
The probability of this issue occurring is very high when retrieving a newly taken Live Photo.
This leads to failure in determining the Live Photo type. How can this issue be resolved?
I cannot find anything documentation re: isPrivacySensitiveAlbum. I've granted my app access to all photos. Not sure what else to try
Code that triggers the crash:
let options = PHFetchOptions()
options.fetchLimit = 1
let assetColl = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [localId], options: options)
if assetColl.count > 0 {
if let asset = PHAsset.fetchKeyAssets(in: assetColl.firstObject!, options: options)
stack trace from here on
`2023-04-15 06:34:41.628537-0700 DPF[33615:6484880] -[PHCollectionList isPrivacySensitiveAlbum]: unrecognized selector sent to instance 0x7ff09232aec0
2023-04-15 06:34:41.632378-0700 DPF[33615:6484880] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PHCollectionList isPrivacySensitiveAlbum]: unrecognized selector sent to instance 0x7ff09232aec0'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff80045478b __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80004db73 objc_exception_throw + 48
2 CoreFoundation 0x00007ff8004638c4 +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0
3 CoreFoundation 0x00007ff800458c66 ___forwarding___ + 1443
4 CoreFoundation 0x00007ff80045ae08 _CF_forwarding_prep_0 + 120
5 Photos 0x00007ff80b8480e1 +[PHAsset fetchKeyAssetsInAssetCollection:options:] + 86
6 DPF 0x0000000100791029 $s3DPF16AlbumListFetcherV22loadKeyImageForLocalIdySo7UIImageCSgSSYaFTY0_ + 569`
The sample code in the Apple documentation found in PHCloudIdentifier does not compile in xCode 13.2.1.
Can the interface for identifier conversion be clarified so that the answer values are more accessible/readable. The values are 'hidden' inside a Result enum
It was difficult (for me) to rewrite the sample code because I made the mistake of interpreting the Result type as a tuple. Result type is really an enum.
Using the Result type as the return from library.cloudIdentifierMappings(forLocalIdentifiers: ) and .localIdentifierMappings(
for: )
puts the actual mapped identifiers inside the the enum where they need additional access via a .stringValue message or an evaluation of an element of the result enum.
For others finding the same compile issue, here is a working version of the sample code. This compiles in xCode 13.2.1.
func localId2CloudId(localIdentifiers: [String]) -> [String] {
var mappedIdentifiers = [String]()
let library = PHPhotoLibrary.shared()
let iCloudIDs = library.cloudIdentifierMappings(forLocalIdentifiers: localIdentifiers)
for aCloudID in iCloudIDs {
let cloudResult: Result = aCloudID.value
// Result is an enum .. not a tuple
switch cloudResult {
case .success(let success):
let newValue = success.stringValue
mappedIdentifiers.append(newValue)
case .failure(let failure):
// do error notify to user
}
}
return mappedIdentifiers
}
``` swift func
func cloudId2LocalId(assetCloudIdentifiers: [PHCloudIdentifier]) -> [String] {
// patterned error handling per documentation
var localIDs = [String]()
let localIdentifiers: [PHCloudIdentifier: Result<String, Error>] = PHPhotoLibrary.shared() .localIdentifierMappings(
for: assetCloudIdentifiers)
for cloudIdentifier in assetCloudIdentifiers {
guard let identifierMapping = localIdentifiers[cloudIdentifier] else {
print("Failed to find a mapping for \(cloudIdentifier).")
continue
}
switch identifierMapping {
case .success(let success):
localIDs.append(success)
case .failure(let failure) :
let thisError = failure as? PHPhotosError
switch thisError?.code {
case .identifierNotFound:
// Skip the missing or deleted assets.
print("Failed to find the local identifier for \(cloudIdentifier). \(String(describing: thisError?.localizedDescription)))")
case .multipleIdentifiersFound:
// Prompt the user to resolve the cloud identifier that matched multiple assets.
print("Found multiple local identifiers for \(cloudIdentifier). \(String(describing: thisError?.localizedDescription))")
// if let selectedLocalIdentifier = promptUserForPotentialReplacement(with: thisError.userInfo[PHLocalIdentifiersErrorKey]) {
// localIDs.append(selectedLocalIdentifier)
default:
print("Encountered an unexpected error looking up the local identifier for \(cloudIdentifier). \(String(describing: thisError?.localizedDescription))")
}
}
}
return localIDs
}
I have enabled runtime concurrency warnings to check for future problems concerning concurrency: Build Setting / Other Swift Flags:
-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks
When trying to call the async form of PHPhotoLibrary.shared().performChanges{} I get the following runtime warning: warning: data race detected: @MainActor function at ... was not called on the main thread in the line containing performChanges.
My sample code inside a default Xcode multi platform app template is as follows:
import SwiftUI
import Photos
@MainActor
class FotoChanger{
func addFotos() async throws{
await PHPhotoLibrary.requestAuthorization(for: .addOnly)
try! await PHPhotoLibrary.shared().performChanges{
let data = NSDataAsset(name: "Swift")!.data
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .photo, data: data, options: PHAssetResourceCreationOptions())
}
}
}
struct ContentView: View {
var body: some View {
ProgressView()
.task{
try! await FotoChanger().addFotos()
}
}
}
You would have to have a Swift data asset inside the asset catalog to run the above code, but the error can even be recreated if the data is invalid.
But what am I doing wrong? I have not found a way to run perform changes, the block or whatever causes the error on the main thread.
PS: This is only test code to show the problem, don't mind the forced unwraps.