permissions.ios.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 CheckOptions = string | { type: string }
  7. type RequestOptions = string | { type: string, rationale?: Rationale }
  8. const permissionTypes = [
  9. 'location',
  10. 'camera',
  11. 'photo',
  12. 'notification'
  13. ]
  14. const DEFAULTS = {
  15. location: 'whenInUse',
  16. notification: ['alert', 'badge', 'sound'],
  17. }
  18. class ReactNativePermissions {
  19. canOpenSettings: () => Promise<boolean> = () =>
  20. PermissionsIOS.canOpenSettings()
  21. openSettings: () => Promise<*> = () => PermissionsIOS.openSettings()
  22. getTypes: () => Array<string> = () => permissionTypes
  23. check = (permission: string, options?: CheckOptions): Promise<Status> => {
  24. if (!permissionTypes.includes(permission)) {
  25. const error = new Error(
  26. `ReactNativePermissions: ${
  27. permission
  28. } is not a valid permission type on iOS`,
  29. )
  30. return Promise.reject(error)
  31. }
  32. let type
  33. if (typeof options === 'string') {
  34. type = options
  35. } else if (options && options.type) {
  36. type = options.type
  37. }
  38. return PermissionsIOS.getPermissionStatus(
  39. permission,
  40. type || DEFAULTS[permission],
  41. )
  42. }
  43. request = (permission: string, options?: RequestOptions): Promise<Status> => {
  44. if (!permissionTypes.includes(permission)) {
  45. const error = new Error(
  46. `ReactNativePermissions: ${
  47. permission
  48. } is not a valid permission type on iOS`,
  49. )
  50. return Promise.reject(error)
  51. }
  52. if (permission == 'backgroundRefresh') {
  53. const error = new Error(
  54. 'ReactNativePermissions: You cannot request backgroundRefresh',
  55. )
  56. return Promise.reject(error)
  57. }
  58. let type
  59. if (typeof options === 'string') {
  60. type = options
  61. } else if (options && options.type) {
  62. type = options.type
  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. export default new ReactNativePermissions()