在 iOS 10 中请求相机和库的权限 - Info.plist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39631256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:19:27  来源:igfitidea点击:

Request Permission for Camera and Library in iOS 10 - Info.plist

iosswiftwkwebview

提问by Alamri

I have implemented a WKWebView in an app. there's a file input in the shown web page where it should import an image from photos. Whenever i press on that input and select either "Take Photo" or "Photo Library" the app suddenly crash, which I believe is because the app is missing the permission to either take a photo or import from library.

我在应用程序中实现了 WKWebView。在显示的网页中有一个文件输入,它应该从照片中导入图像。每当我按下该输入并选择“拍照”或“照片库”时,应用程序就会突然崩溃,我认为这是因为该应用程序缺少拍照或从库中导入的权限。

How do I push a permission request when the user select one of the mentioned methods (Take Photo or Photo Library)?

当用户选择上述方法之一(拍照或照片库)时,如何推送权限请求?

I use Swift 3.0 with WKWebView.

我将 Swift 3.0 与 WKWebView 一起使用。

回答by George Vardikos

You can also request for access programmatically, which I prefer because in most cases you need to know if you took the access or not.

您还可以以编程方式请求访问,我更喜欢这种方式,因为在大多数情况下,您需要知道您是否获得了访问权限。

Swift 4 update:

斯威夫特 4 更新:

    //Camera
    AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
        if response {
            //access granted
        } else {

        }
    }

    //Photos
    let photos = PHPhotoLibrary.authorizationStatus()
    if photos == .notDetermined {
        PHPhotoLibrary.requestAuthorization({status in
            if status == .authorized{
                ...
            } else {}
        })
    }

You do not share code so I cannot be sure if this would be useful for you, but general speaking use it as a best practice.

您不共享代码,因此我无法确定这是否对您有用,但一般而言,将其用作最佳实践。

回答by Kirit Modi

You have to add the below permission in Info.plist. More Referance

您必须在 Info.plist 中添加以下权限。更多参考

Camera :

相机 :

Key       :  Privacy - Camera Usage Description   
Value     :  $(PRODUCT_NAME) camera use

Photo :

照片 :

Key       :  Privacy - Photo Library Usage Description    
Value     :  $(PRODUCT_NAME) photo use

回答by Vishal Vaghasiya

File: Info.plist

文件:Info.plist

Camera

相机

<key>NSCameraUsageDescription</key>
<string>camera description.</string>

Photos

相片

<key>NSPhotoLibraryUsageDescription</key>
<string> photos description.</string>

Save Photos

保存照片

  <key>NSPhotoLibraryAddUsageDescription</key>
  <string> photos add description.</string>

Location

地点

<key> NSLocationWhenInUseUsageDescription</key>
<string> location description.</string>

Apple Music:

苹果音乐:

<key>NSAppleMusicUsageDescription</key>
<string>My description about why I need this capability</string>

Calendar

日历

<key>NSCalendarsUsageDescription</key>
<string>My description about why I need this capability</string>

Siri

Siri

<key>NSSiriUsageDescription</key>
<string>My description about why I need this capability</string>

回答by Joel Teply

Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:

使用上面提到的 plist 设置和适当的访问器(AVCaptureDevice 或 PHPhotoLibrary),但如果你真的需要,也要提醒它们并将它们发送到设置,如下所示:

Swift 4.0 and 4.1

斯威夫特 4.0 和 4.1

func proceedWithCameraAccess(identifier: String){
    // handler in .requestAccess is needed to process user's answer to our request
    AVCaptureDevice.requestAccess(for: .video) { success in
      if success { // if request is granted (success is true)
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: identifier, sender: nil)
        }
      } else { // if request is denied (success is false)
        // Create Alert
        let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)

        // Add "OK" Button to alert, pressing it will bring you to the settings app
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        // Show the alert with animation
        self.present(alert, animated: true)
      }
    }
  }

回答by Ed of the Mountain

File: Info.plist

文件:Info.plist

For Camera:

对于相机

<key>NSCameraUsageDescription</key>
<string>You can take photos to document your job.</string>

For Photo Library, you will want this one to allow app user to browse the photo library.

对于Photo Library,您将希望使用这个来允许应用程序用户浏览照片库。

<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach to reports.</string>

回答by elarctheitroadis

Swift 5The easiest way to add permissions without having to do it programatically, is to open your info.plist file and select the + next to Information Property list. Scroll through the drop down list to the Privacy options and select Privacy Camera Usage Description for accessing camera, or Privacy Photo Library Usage Description for accessing the Photo Library. Fill in the String value on the right after you've made your selection, to include the text you would like displayed to your user when the alert pop up asks for permissions. Camera/Photo Library permission

Swift 5无需以编程方式添加权限的最简单方法是打开您的 info.plist 文件并选择信息属性列表旁边的 +。滚动下拉列表至隐私选项,然后选择隐私相机使用说明以访问相机,或选择隐私照片库使用说明以访问照片库。做出选择后,填写右侧的字符串值,以包含您希望在弹出警报请求权限时向用户显示的文本。相机/照片库权限

回答by marcomoreira92

To ask permission for the photo app you need to add this code (Swift 3):

要请求照片应用程序的许可,您需要添加以下代码(Swift 3)

PHPhotoLibrary.requestAuthorization({ 
       (newStatus) in 
         if newStatus ==  PHAuthorizationStatus.authorized { 
          /* do stuff here */ 
    }?
})

回答by Doci

Great way of implementing Camera session in Swift 5, iOS 13

Swift 5iOS 13中实现相机会话的好方法

https://github.com/egzonpllana/CameraSession

https://github.com/egzonpllana/CameraSession

Camera Session is an iOS app that tries to make the simplest possible way of implementation of AVCaptureSession.

Camera Session 是一个 iOS 应用程序,它试图以最简单的方式实现 AVCaptureSession。

Through the app you can find these camera session implemented:

通过该应用程序,您可以找到实现的这些摄像头会话:

  • Native camera to take a picture or record a video.
  • Native way of importing photos and videos.
  • The custom way to select assets like photos and videos, with an option to select one or more assets from the Library.
  • Custom camera to take a photo(s) or video(s), with options to hold down the button and record.
  • Separated camera permission requests.
  • 用于拍照或录制视频的本机相机。
  • 导入照片和视频的原生方式。
  • 选择照片和视频等资产的自定义方式,可以选择从库中选择一项或多项资产。
  • 自定义相机拍摄照片或视频,可选择按住按钮并录制。
  • 单独的相机权限请求。

The custom camera features like torchand rotate cameraoptions.

自定义相机功能,如手电筒旋转相机选项。

回答by DronPop

I wrote an extension that takes into account all possible cases:

我写了一个扩展,考虑到所有可能的情况:

  • If access is allowed, then the code onAccessHasBeenGrantedwill be run.
  • If access is not determined, then requestAuthorization(_:)will be called.
  • If the user has denied your app photo library access, then the user will be shown a window offering to go to settings and allow access. In this window, the "Cancel" and "Settings" buttons will be available to him. When he presses the "settings" button, your application settings will open.
  • 如果允许访问,则将onAccessHasBeenGranted运行代码。
  • 如果未确定访问,requestAuthorization(_:)则将调用。
  • 如果用户拒绝访问您的应用程序照片库,则将向用户显示一个窗口,提供转到设置并允许访问的窗口。在此窗口中,他可以使用“取消”和“设置”按钮。当他按下“设置”按钮时,您的应用程序设置将打开。

Usage example:

用法示例:

PHPhotoLibrary.execute(controller: self, onAccessHasBeenGranted: {
    // access granted... 
})

Extension code:

扩展代码:

import Photos
import UIKit

public extension PHPhotoLibrary {

   static func execute(controller: UIViewController,
                       onAccessHasBeenGranted: @escaping () -> Void,
                       onAccessHasBeenDenied: (() -> Void)? = nil) {

      let onDeniedOrRestricted = onAccessHasBeenDenied ?? {
         let alert = UIAlertController(
            title: "We were unable to load your album groups. Sorry!",
            message: "You can enable access in Privacy Settings",
            preferredStyle: .alert)
         alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
         alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
               UIApplication.shared.open(settingsURL)
            }
         }))
         controller.present(alert, animated: true)
      }

      let status = PHPhotoLibrary.authorizationStatus()
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAccessHasBeenGranted)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAccessHasBeenGranted()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   }

}

private func onNotDetermined(_ onDeniedOrRestricted: @escaping (()->Void), _ onAuthorized: @escaping (()->Void)) {
   PHPhotoLibrary.requestAuthorization({ status in
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAuthorized)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAuthorized()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   })
}