簡體   English   中英

根據 SwiftUI 的權限更改視圖?

[英]Change view based on permissions with SwiftUI?

我編寫了一個需要照片庫權限的應用程序。 擔心的是它在應用程序啟動后立即需要它,因此它必須在應用程序啟動時檢查授予的權限,如果不確定,則請求它,等待結果並再次更改視圖,我'我的頭已經斷了三天了? 但我做不到:你能幫幫我嗎? 這是我的代碼:

內容視圖:

    struct ContentView: View {
    var auth = false
    @State var limitedAlert = false
    @State var statusPhoto = 0
    @State var AuthPictStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
    var body: some View {
        VStack{}
            .task{
                while true {
                    AuthPictStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
                }
            }
            if AuthPictStatus == .authorized {
                CardView(canExecute: true)
            }
            if AuthPictStatus == .denied {
                PhotoLybrairyDenied()
            }
            if AuthPictStatus == .limited {
                CardView(canExecute: true)
                    .onAppear{limitedAlert = true}
                    .alert(isPresented: $limitedAlert) {
                        Alert(
                            title: Text("L'accès au photos est limitées !"),
                            message: Text("Votre autorisations ne nous permets d'accèder a seulement certaines photos ! De se fait, nous ne pouvons pas trier l'intégralité de vos photos !"),
                            primaryButton: .destructive(Text("Continuer malgré tout"), action: {
                                
                            }),
                            secondaryButton: .default(Text("Modifier l'autorisation"), action: { // 1
                                guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                                            return
                                        }

                                        if UIApplication.shared.canOpenURL(settingsUrl) {
                                            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                                                print("Settings opened: \(success)") // Prints true
                                            })
                                        }
                                    
                            })
                        )
                    }
                }
            if AuthPictStatus == .notDetermined {
                CardView(canExecute: false)
                    .blur(radius: 5)
                    .disabled(true)
            }
        
        
    }
}

照片刪除應用程序:

//
//  PhotoDeleteApp.swift
//  PhotoDelete
//
//  Created by Rémy on 09/04/2022.
//

import SwiftUI
import Photos

@main
struct PhotoDeleteApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear{
                    PHPhotoLibrary.requestAuthorization({status in })
                }
        }
    }
}
//
//  PhotoDeleteApp.swift
//  PhotoDelete
//
//  Created by Rémy on 09/04/2022.
//

import SwiftUI
import Photos

@main
struct PhotoDeleteApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear{
                    PHPhotoLibrary.requestAuthorization({status in })
                }
        }
    }
}

我處理過與照片權限相關的類似問題(我在 SwiftUI 和 iOS 14)。 我做了一些故障排除,發現使用SwiftUIViewDelegate實現自定義授權狀態沒有按預期工作。 我做了一個測試並選擇了“僅選定的照片”(這應該使授權狀態為.limited )。 除了授權狀態不受限制,但.authorized.denied僅當我完全拒絕訪問時。

所以在我的 SwiftUI 應用程序中,我放棄了花哨的嘗試並使用了 package 權限 SwiftUI。它提供了一些關於如何自定義消息的文檔,但它使用一個表來處理權限,使實現無憂無慮(它沒有解決.limited情況或者我描述的用戶選擇有限實際上是完全訪問的錯誤)。

我的實現看起來像這樣,在我的入口點@main中,在WindowGroup { }內的第一個 View HomeTabView(homeViewModel: homeViewModel)

.JMModal(showModal: $homeViewModel.showingPermissionsSelector, for: [.photo], autoDismiss: true, autoCheckAuthorization: false, restrictDismissal: false)
            .changeHeaderTo("App Permissions")
            .changeHeaderDescriptionTo("Export and Import of images requires photos access.")
            .changeBottomDescriptionTo("Allowing the app to import photos provides the app access to airdropped and saved user photos.")

我建議您嘗試一下,看看它是否足以滿足您的目的。 要在您的項目中包含權限 SwiftUI package,在左側面板中為您的項目添加權限 go,在頂部欄中添加 select“項目”,go 到“包依賴項”,按 + 按鈕,然后搜索權限 89486825選項,但只添加PermissionsSwiftUIPhoto 如果您需要其他權限,有很多可供選擇。

我有權限綁定到“導入照片”按鈕(在子視圖中)因此 HomeTabViewModel 屬於parent

Button(action: {
            let authorization = PHPhotoLibrary.authorizationStatus()
            print("switching on image authorization status: \(authorization)")
            switch authorization {
            case .notDetermined:
                parent.homeVM.showingPermissionsSelector = true
            case .restricted:
                parent.homeVM.showingPermissionsSelector = true
            case .denied:
                parent.homeVM.showingPermissionsSelector = true
            case .authorized:
                parent.homeVM.showingImagePicker = true
            case .limited:
                parent.homeVM.showingImagePicker = true // I've never reached this case (bug?)
            @unknown default:
                print("unhandled authorization status")
                break
            }

我的 homeViewModel(例如簡化版)

import SwiftUI

final class HomeTabViewModel: ObservableObject {
    @Published var showingPermissionsSelector = false
    @Published var showingImagePicker         = false
   // @Published var showingLimitedSelector = false // Thought I would need this but I dont because there is no differentiation between .authorized and .denied from my testing
}

但您可以讓您的應用執行.onAppear { // check auth status and change $homeViewModel.showingPermissionsSelector based on your code's logic}

我處理了與 Rémy 相同的問題,一方面我很高興我不必區分.limited.authorized因為它讓我們更容易,但它也有點怪異因為它意味着照片授權是在 iOS 上沒有按預期工作......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM