我有一个包含WKWebView
的应用程序,并且在Web视图中,我们可以附加照片库中的图像。当从Safari或Chrome打开页面但在我的应用程序照片选项中未打开时,此功能正常运行。
我已经搜索了几个答案,但它们告诉您注入自定义JavaScript来附加侦听器。但是什么都行不通。
您需要在代码中手动为应用授予权限。这样您的WKWebView
可以打开图库。
在Info.plist文件中添加以下两个键:
<key>NSPhotoLibraryUsageDescription</key>
<string>Needs permission to select photos</string>
<key>NSCameraUsageDescription</key>
<string>Needs permission to take photos</string>
并添加以下代码以在WKWebView
中加载图片附件功能之前询问照片权限(不要忘记import Photos
框架):
let status = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
print("already authorized")
} else {
PHPhotoLibrary.requestAuthorization({(_ status: PHAuthorizationStatus) -> Void in
switch status {
case .authorized:
print("Authorized")
case .denied:
print("Denied")
case .notDetermined:
print("Not determined")
case .restricted:
print("Restricted")
@unknown default:
print("Unknown")
}
})
}