permissions.ios.js 2.4 KB

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