Hi, I am trying to store persistent changes to the photo library.
I know I can use a PHPersistentChangeToken to get the changes since that token, but I am not sure how to serialize this object and save it into a file.
I am also wondering if you can serialize a PHPersistentChangeFetchResult and store that in a file.
Cheers.
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,
I want to create a photo portfolio (in VueJS) and I'd like to use my icloud photo library to store the photos.
Is there an API that allows me to access one or more albums in my photo library?
It seems like there is no way to do this but I am having trouble wrapping my head around this posibility. How is this not a thing?
Where is PhotoPicker for tvOS? Why is it missing?
Now I use AVFoundation framework to get the photo output, but the image aspect ratio is 4:3. But according to the Camera app in the iPhone 13 Pro, it has server image aspect ratio: 4:3, 16:9 and 1:1 when take the proraw image. So how can I get the 1:1, 16:9 aspect ratio proraw image?
After I do some research, I find that no matter you use which kinds of camera in the iPhone 11, 12, 13, 14, 15 or Pro, the result image is always 4:3, 1:1 and 16:9 come from the 4:3 cropping. If it is true, how can I crop the proraw file without any data lossing?
My developer environment:
iPhone 13 Pro
iOS 16.7
xcode 14.3.1
This is the session configuration code for the camera device configuration.
session.beginConfiguration()
/*
Do not create an AVCaptureMovieFileOutput when setting up the session because
Live Photo is not supported when AVCaptureMovieFileOutput is added to the session.
*/
session.sessionPreset = .photo
// Add video input.
do {
var defaultVideoDevice: AVCaptureDevice?
if let backCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) {
// If a rear dual camera is not available, default to the rear wide angle camera.
defaultVideoDevice = backCameraDevice
} else if let frontCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) {
// If the rear wide angle camera isn't available, default to the front wide angle camera.
defaultVideoDevice = frontCameraDevice
}
guard let videoDevice = defaultVideoDevice else {
print("Default video device is unavailable.")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
if session.canAddInput(videoDeviceInput) {
session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
print("Couldn't add video device input to the session.")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
} catch {
print("Couldn't create video device input: \(error)")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
// check the lens list
let camerasOptions = videoDeviceDiscoverySession.devices
var availableCameras: [AVCaptureDevice.DeviceType] = []
if camerasOptions.isEmpty {
print("no camera devices")
} else {
for camera in camerasOptions {
if camera.deviceType == .builtInUltraWideCamera || camera.deviceType == .builtInWideAngleCamera || camera.deviceType == .builtInTelephotoCamera {
if !availableCameras.contains(camera.deviceType) {
availableCameras.append(camera.deviceType)
}
}
}
}
DispatchQueue.main.async {
self.lensList = availableCameras
}
// Add the photo output.
if session.canAddOutput(photoOutput) {
session.addOutput(photoOutput)
photoOutput.isHighResolutionCaptureEnabled = true
photoOutput.maxPhotoQualityPrioritization = .quality
print(photoOutput.isAppleProRAWSupported)
// Use the Apple ProRAW format when the environment supports it.
photoOutput.isAppleProRAWEnabled = photoOutput.isAppleProRAWSupported
DispatchQueue.main.async {
self.isSupportAppleProRaw = self.photoOutput.isAppleProRAWSupported
}
} else {
print("Could not add photo output to the session")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
session.commitConfiguration()
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?
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
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)
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?
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'
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
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
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!
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))")
}
}
}
}
}
}
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?
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.
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.
**does anyone know what this is, means, or is affiliated to ? **
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.
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, 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?