To be able to use MPMusicPlayerController.systemMusicPlayer, I was using the code below to request authorization if we get status ( let status = MPMediaLibrary.authorizationStatus() ) was notDetermined.
But that code crashes application after I switch to swift6.
Is there anyone overcome this somehow.
MPMediaLibrary.requestAuthorization { newStatus in
if newStatus == .authorized {
self.mpmusicLibraryAuthorized = true
print("Media Library access authorized")
} else {
print("Media Library access denied or restricted")
self.mpmusicLibraryAuthorized = false
}
}
Put your code into a @MainActor
method, and do not use the old completion handler based call; call this method:
class func requestAuthorization() async -> MPMediaLibraryAuthorizationStatus
Here's the actual code from my own app:
@MainActor func haveMusicLibraryAccess() async -> Bool {
let status = MPMediaLibrary.authorizationStatus()
switch status {
case .notDetermined:
let stat = await MPMediaLibrary.requestAuthorization()
return stat == .authorized
case .denied:
noAuthorizationAlertDenied()
return false
case .restricted:
noAuthorizationAlertRestricted()
return false
case .authorized:
return true
@unknown default:
fatalError()
}
}
(The two noAuthorization...
methods are just my app's way of explaining to the user that we cannot proceed without authorization. You don't have to imitate that approach.)