In my app I use PhotosPicker to select images. After selection the images the image data will be saved in a CoreData entity - this works fine.
However, When the user wants to add more images and go back to adding photos with PhotosPicker - how can I reference the already added images and show them as selected in PhotosPicker?
The imageIdentifier is not allowed to use, so how can I do get a reference to the selected images to display them as selected in PhotosPicker?
Thanks for any hint!
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
87 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hello Apple Developer Community,
I'm excited to make my first post here and am seeking guidance for a feature I'd like to implement in my app. My objective is to enable users to select an image and crop it. Ideally, there should be a visible indicator, like a rectangle, to show the area that will be cropped. Upon clicking the save button, the image would be saved with the selected cropped area.
I'm aiming for functionality to the image editor in the Photos app. Is there a straightforward method or integration for this that adheres to Apple's native frameworks, without resorting to external GitLab repositories?
Thank you in advance for your assistance.
Best regards,
Nicola
Hello! I'm trying to save videos asynchronously. I've already used performChanges without the completionHandler, but it didn't work. Can you give me an example? Consider that the variable with the file URL is named fileURL. What would this look like asynchronously?
Hello, I am experiencing an unexpected issue related to PhotosKit, where an occasional crash is occurring in an area it shouldn't. I've provided the crash log below for reference below:
Last Exception Backtrace:
0 CoreFoundation 0x1aa050860 __exceptionPreprocess + 164
1 libobjc.A.dylib 0x1a2363c80 objc_exception_throw + 60
2 CoreFoundation 0x1a9f68218 -[__NSDictionaryM setObject:forKeyedSubscript:] + 1184
3 Photos 0x1c11cb178 -[PHCloudIdentifierLookup _lookupCodeSpecificCloudIdentifierStrings:forIdentifierCode:] + 572
4 Photos 0x1c11cb278 -[PHCloudIdentifierLookup _lookupLocalIdentifiersForIdentifierCode:codeSpecificCloudIdentifierStrings:] + 92
5 Photos 0x1c11cbbec __69-[PHCloudIdentifierLookup lookupLocalIdentifiersForCloudIdentifiers:]_block_invoke + 88
6 CoreFoundation 0x1a9f67d70 NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK + 24
7 CoreFoundation 0x1a9f67bec -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] + 288
8 Photos 0x1c11cbb40 -[PHCloudIdentifierLookup lookupLocalIdentifiersForCloudIdentifiers:] + 488
9 Photos 0x1c125e6e4 -[PHPhotoLibrary(CloudIdentifiers) localIdentifierMappingsForCloudIdentifiers:] + 96
10 Photos 0x1c1104f18 0x1c1101000 + 16152
"exceptionReason" : {"arguments":["-[__NSDictionaryM setObject:forKeyedSubscript:]"],"format_string":"*** %s: key cannot be nil","name":"NSInvalidArgumentException","type":"objc-exception","composed_message":"*** -[__NSDictionaryM setObject:forKeyedSubscript:]: key cannot be nil","class":"NSException"},
The crash can be recreated by calling PHPhotoLibrary.cloudIdentifierMappings(forLocalIdentifiers:) with random identifiers, as demonstrated below:
let cloudIdentifiers = (0...10).map { _ in PHCloudIdentifier(stringValue: UUID().uuidString) } let localIdsMap = PHPhotoLibrary.shared().localIdentifierMappings(for: cloudIdentifiers)
I've noticed that the method seems to crash consistently when an incorrect cloud identifier is input. This is surprising to me since the return type is [PHCloudIdentifier : Result<String, Error>], so I was anticipating an explicit error.
The issue can be reproduced on both Xcode 15.0 & iOS 17.2 and Xcode 14.3.1 & iOS 16.0.
While I'm fairly certain that only valid identifiers are used in my app, I would still like to know if there is a potential way to validate a cloud identifier prior to accessing this method?
Hello, I am experiencing an unexpected issue related to PhotosKit, where an occasional crash is occurring in an area it shouldn't. I've provided the crash log below for reference.
The crash can be recreated by calling PHPhotoLibrary.cloudIdentifierMappings(forLocalIdentifiers:) with random identifiers, as demonstrated below:
let cloudIdentifiers = (0...10).map { _ in PHCloudIdentifier(stringValue: UUID().uuidString) }
let localIdsMap = PHPhotoLibrary.shared().localIdentifierMappings(for: cloudIdentifiers)
I've noticed that the method seems to crash consistently when an incorrect cloud identifier is input. This is surprising to me since the return type is [PHCloudIdentifier : Result<String, Error>], so I was anticipating an explicit error.
The issue can be reproduced on both Xcode 15.0 & iOS 17.2 and Xcode 14.3.1 & iOS 16.0.
While I'm fairly certain that only valid identifiers are used in my app, I would still like to know if there is a potential way to validate a cloud identifier prior to accessing this method?
When I embedded a PhotosPickerView() in popover,
it won't works:
struct PhotoPickerTest: View {
@State private var selectedPhotoItem: PhotosPickerItem?
@State var isTaped: Bool = false
var body: some View {
Button("", systemImage: "plus") {
isTaped = true
}
.popover(isPresented: $isTaped) {
PhotoPickerView()
}
}
func PhotoPickerView() -> some View {
PhotosPicker(selection: $selectedPhotoItem) {
Image(systemName: "photo")
}
}
}
but if I just replace "popover" to "sheet", it works fine:
struct PhotoPickerTest: View {
@State private var selectedPhotoItem: PhotosPickerItem?
@State var isTaped: Bool = false
var body: some View {
Button("", systemImage: "plus") {
isTaped = true
}
.sheet(isPresented: $isTaped) {
PhotoPickerView()
}
}
func PhotoPickerView() -> some View {
PhotosPicker(selection: $selectedPhotoItem) {
Image(systemName: "photo")
}
}
}
I think it's a bug, and bothered me a lot, hope apple engineers can fix it.
Hello,
We have a Photo Vault app. We were hiding users' photos behind a semi-functional calculator. But after rejection, we thought "decoy functionality" meant we needed to remove this fake calculator feature. We removed it, and tried many things to solve this issue, but couldn't understand what Apple wants us to change. We've been trying to contact Apple for more details, but they keep sending the same message every time.
Helps appreciated. Here is the rejection message:
.
Your app uses public APIs in an unapproved manner, which does not comply with guideline 2.5.1 of the App Store Review Guidelines.
Specifically, we found that your app uses a decoy functionality to hide a user’s photos, which is not an appropriate use of the Photos API.
Since there is no accurate way of predicting how an API may be modified and what effects those modifications may have, Apple does not permit unapproved uses of public APIs in App Store apps.
Next Steps
Please revise your app to ensure that documented APIs are used in the manner prescribed by Apple.
It would be appropriate to remove any features in your app that use a decoy functionality to hide a user's photos from your app.
If there are no alternatives for providing the functionality your app requires, you can use Feedback Assistant to submit an enhancement request.
**does anyone know what this is, means, or is affiliated to ? **
I'm running this SwiftUI sample app for photos without any modifications except for adding my developer profile, which is necessary to build it. When I tap on the thumbnail to see the photo library (after granting access to my photo library), I see that some of the thumbnails are stuck in a loading state, and when I tap on thumbnails, I only see a low-resolution image (the thumbnail), not the full-resolution image that should load.
In the console I can see this error that occurs when tapping on a thumbnail to see the full-resolution image:
CachedImageManager requestImage error: The operation couldn’t be completed. (PHPhotosErrorDomain error 3164.)
When I make a few modifications necessary to run the app as a native macOS app, all the thumbnails load immediately, and clicking on them reveals the full-resolution images.
Even with sample code from Apple, the same warning forever.
"Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)""
Failed to log access with error: access=<PATCCAccess 0x28316b070> accessor:<<PAApplication 0x283166df0 identifierType:auditToken identifier:{pid:1456, version:3962}>> identifier:2EE1A54C-344A-40AB-9328-3F8E8B5E8A85 kind:intervalEvent timestampAdjustment:0 visibilityState:0 assetIdentifierCount:0 tccService:kTCCServicePhotos, error=Error Domain=NSCocoaErrorDomain Code=4097 "connection to service with pid 235 named com.apple.privacyaccountingd" UserInfo={NSDebugDescription=connection to service with pid 235 named com.apple.privacyaccountingd}
Entitlements are reviewed.
var config = PHPickerConfiguration()
config.filter = PHPickerFilter.images
I want only 'png' files to be displayed when the PHPickerViewController photo list is opened.
I've read this post : https://developer.apple.com/forums/thread/687415
In this post, it is mentioned that filtering image formats by PHPickerConfiguration is not possible (2 years ago).
Is it still not possible? Has issue 71832162 not been resolved?
From IOS 17.
Have an issue when saving video and reading it from PHPickerViewController. Video become into jpeg file
Code save video and I saw reason because i changed creationDate. But IOS 16 no bug here
doVertifyAccessAblum() {
DispatchQueue.global(qos: .background).async {
if let url = URL(string: videoURL), let urlData = NSData(contentsOf: url) {
let galleryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let filePath="\(galleryPath)/\(url.lastPathComponent).mp4"
DispatchQueue.main.async {
urlData.write(toFile: filePath, atomically: true)
PHPhotoLibrary.shared().performChanges({
let changeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
changeRequest?.creationDate = Date()
}) { success, error in
LOGGING.debug("Save video with status: success=\(success) error=\(String(describing: error))")
}
}
}
}
}
}
Hello,
We are trying to take pictures or grab frames using an iOS Phone 15 Pro. The items are moving down a conveyor belt. All we need to do is grab a photo of the item and crop it and save it as a jpg. Any ideas on what the best way to accomplish this is?
Thanks!
Hello,
I'm currently investigating the possibility of accessing my photos stored on my iCloud via a dedicated API, in order to create a photo portfolio.
However, after extensive research, I haven't found any documentation or public API allowing such access. I wonder if there are any future plans to make such an API available to third-party developers.
I would be grateful if you could provide me with information regarding the possibility of accessing an API for Apple Photos or any other solution you might suggest.
Thank you for your attention and assistance.
Yours sincerely
Owen
Is it possible to retrieve image metadata without requesting additional permission with the new SwiftUI PhotosPicker?
I can access metadata when using
picker( _ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult])
by using itemProvider. But for PhotosPicker, it seems that it's only possible by firstly retrieving PHAsset from PhotosPickerItem, and then by using requestContentEditingInput. Which require authorization for specific photo
First, App has linked with PhotosUI and Photos.
And, this problem never happened when complied with Xcode14.1 and Swift.
New APP is compiled with Xcode15.0.1. Code is not changed.
Step:
Set access "Selected Photos" for APP.
Restart APP. Try to access photos with PHPhotoLibrary functions , and then a system dialog appears. There are two buttons: "Select More Photos..." and "Keep Current Selection".
Choose "Keep Current Selection". (If choose "Select More Photos...", the app will not crash.)
Call "presentLimitedLibraryPicker(from controller: UIViewController)"
Crash log:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PHPhotoLibrary presentLimitedLibraryPickerFromViewController:]: unrecognized selector sent to instance 0x1064d66f0'
guard let rawfilter = CoreImage.CIRAWFilter(imageData: data, identifierHint: nil) else { return }
guard let ciImage = rawfilter.outputImage else { return }
let width = Int(ciImage.extent.width)
let height = Int(ciImage.extent.height)
let rect = CGRect(x: 0, y: 0, width: width, height: height)
let context = CIContext()
guard let cgImage = context.createCGImage(ciImage, from: rect, format: .RGBA16, colorSpace: CGColorSpaceCreateDeviceRGB()) else { return }
print("cgImage prepared")
guard let dataProvider = cgImage.dataProvider else { return }
let rgbaData = CFDataCreateMutableCopy(kCFAllocatorDefault, 0, dataProvider.data)
In iOS 16 this process is much faster than the same process in iOS 17
Is there a method to boost up the decoding speed?
PHPickerViewController 选择图片后直接奔溃 iPhone是 iOS 14+ 系统测试的
![](“https://developer.apple.com/forums/content/attachment/34b6441d-f7a3-4125-95d6-7fb5972c44fa”,“title=微信IMG84.jpg;宽度=1069;高度=1002")
![](“https://developer.apple.com/forums/content/attachment/31e73caf-97fa-46bb-bd5b-1f385c5ef6b8”,“title=微信IMG85.jpg;宽度=809;高度=979")
![](“https://developer.apple.com/forums/content/attachment/da5ef40a-944e-4dea-a30a-1ca19465cf47”,“title=微信IMG86.jpg;宽度=1579;高度=997")
崩溃信息是:
线程 2:“无法从<_NSProgressProxy 0x281b0ed00>中删除键路径 \”fractionCompleted\“ 的观察者 <PUPhotosFileProviderItemProvider 0x28003db80>,因为它未注册为观察者。
B K(英语:B K)
My app uses PHLivePhoto.request to generate live photos, but memory leaks if I use a custom targetSize.
PHLivePhoto.request(withResourceFileURLs: [imageUrl, videoUrl], placeholderImage: nil, targetSize: targetSize, contentMode: .aspectFit) {[weak self] (livePhoto, info) in
Change targetSize to CGSizeZero, problem resolved.
PHLivePhoto.request(withResourceFileURLs: [imageUrl, videoUrl], placeholderImage: nil, targetSize: CGSizeZero, contentMode: .aspectFit) {[weak self] (livePhoto, info) in
I'm trying to provide a mechanism for the user to select a bg image from their photo library. I've got this code which theoretically is getting the data but can't figure out how to convert it to an Image in SwiftUI. I've found plenty of examples on iOS but none workable on MacOS.
This is my implementation of the PhotosPicker on iOS:
PhotosPicker(selection: $vm.selectedBGphoto, matching: .images) {
Label("Select Background Image", systemImage: "photo.on.rectangle")
}
.tint(.purple)
.controlSize(.large)
.onChange(of: vm.selectedBGphoto) { newItem in
Task {
if let data = try? await newItem?.loadTransferable(type: Data.self) {
if let uiImage = UIImage(data: data) {
vm.selectedBGdata = data
vm.bgImage = Image(uiImage: uiImage)
}
}
}
This DOES NOT work on MacOS because of the UIImage reference. How do I convert what I get from PhotosPicker into an Image on MacOS?