Runtime race condition warning when calling PHPhotoLibrary.shared().performChanges async

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.

Answered by Dirk-FU in 800700022

If someone later finds this, the following worked for me

performChanges{@Sendable in ... }

I had the same problem again later with PHImageManager.requestAVAsset{}, the solution is the same.

Accepted Answer

If someone later finds this, the following worked for me

performChanges{@Sendable in ... }

I had the same problem again later with PHImageManager.requestAVAsset{}, the solution is the same.

Thanks a lot, this helped me to get rid of the warning when saving a video to the photo library.

Runtime race condition warning when calling PHPhotoLibrary.shared().performChanges async
 
 
Q