permissions.ios.js 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // @flow
  2. import { NativeModules } from 'react-native'
  3. const PermissionsIOS = NativeModules.ReactNativePermissions
  4. type Status = 'authorized' | 'denied' | 'restricted' | 'undetermined'
  5. type Rationale = { title: string, message: string }
  6. type Options = string | { type: string, rationale?: Rationale }
  7. const permissionTypes = [
  8. 'location',
  9. 'camera',
  10. 'microphone',
  11. 'photo',
  12. 'contacts',
  13. 'event',
  14. 'reminder',
  15. 'bluetooth',
  16. 'notification',
  17. 'backgroundRefresh',
  18. 'speechRecognition',
  19. ]
  20. const DEFAULTS = {
  21. location: 'whenInUse',
  22. notification: ['alert', 'badge', 'sound'],
  23. }
  24. class ReactNativePermissions {
  25. canOpenSettings: () => Promise<boolean> = () =>
  26. PermissionsIOS.canOpenSettings()
  27. openSettings: () => Promise<*> = () => PermissionsIOS.openSettings()
  28. getTypes: () => Array<string> = () => permissionTypes
  29. check = (permission: string, type?: string): Promise<Status> => {
  30. if (!permissionTypes.includes(permission)) {
  31. const error = new Error(
  32. `ReactNativePermissions: ${
  33. permission
  34. } is not a valid permission type on iOS`,
  35. )
  36. return Promise.reject(error)
  37. }
  38. return PermissionsIOS.getPermissionStatus(
  39. permission,
  40. type || DEFAULTS[permission],
  41. )
  42. }
  43. request = (permission: string, options?: Options): Promise<Status> => {
  44. let type
  45. if (typeof options === 'string') {
  46. type = options
  47. } else if (options && options.type) {
  48. type = options.type
  49. }
  50. if (!permissionTypes.includes(permission)) {
  51. const error = new Error(
  52. `ReactNativePermissions: ${
  53. permission
  54. } is not a valid permission type on iOS`,
  55. )
  56. return Promise.reject(error)
  57. }
  58. if (permission == 'backgroundRefresh') {
  59. const error = new Error(
  60. 'ReactNativePermissions: You cannot request backgroundRefresh',
  61. )
  62. return Promise.reject(error)
  63. }
  64. return PermissionsIOS.requestPermission(
  65. permission,
  66. type || DEFAULTS[permission],
  67. )
  68. }
  69. checkMultiple = (permissions: Array<string>): Promise<{ [string]: string }> =>
  70. Promise.all(permissions.map(permission => this.check(permission))).then(
  71. result =>
  72. result.reduce((acc, value, index) => {
  73. const name = permissions[index]
  74. acc[name] = value
  75. return acc
  76. }, {}),
  77. )
  78. }
  79. module.exports = new ReactNativePermissions()