Swiftpack.co - Package - ivanvorobei/SPPermissions

SPPermissions

About

SPPermissions is an API to ask for user permissions using Swift. The API provides for three UI options (list, dialog & native).

The UI/UX is in an Apple style and supports iPad, dark mode, & tvOS.

Also you can check the state permissions using the API.

If you like the project, don't forget to put star ★ and follow me on GitHub:

https://github.com/ivanvorobei

Navigate

Requirements

Swift 4.2 & 5.0. Ready for use on iOS 11+

Installation

CocoaPods:

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate SPPermissions into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'SPPermissions/Notification'

Due to Apple's new policy regarding permission access you need to specifically define what kind of permissions you want to access using subspecs. For example if you want to access Camera, Location & Microphone you define the following:

pod 'SPPermissions/Camera'
pod 'SPPermissions/Location'
pod 'SPPermissions/Microphone'
Available subspecs

pod 'SPPermissions/Camera'
pod 'SPPermissions/Contacts'
pod 'SPPermissions/Calendar'
pod 'SPPermissions/PhotoLibrary'
pod 'SPPermissions/Notification'
pod 'SPPermissions/Microphone'
pod 'SPPermissions/Reminders'
pod 'SPPermissions/SpeechRecognizer'
pod 'SPPermissions/Location'
pod 'SPPermissions/Motion'
pod 'SPPermissions/MediaLibrary'
pod 'SPPermissions/Bluetooth'
pod 'SPPermissions/Tracking'

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

To integrate SPPermissions into your Xcode project using Xcode 11, specify it in File > Swift Packages > Add:

https://github.com/ivanvorobei/SPPermissions

After integrate need add configuration. See example SPPermissionsConfiguration.xcconfig file or example project. If you don't know how add configuration file, see this short video.

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate SPPermissions into your Xcode project using Carthage, specify it in your Cartfile:

github "ivanvorobei/SPPermissions"

By default available all permissions. You can provide custom build flags before building the dynamic framework to only compile with permissions you request. Open file SPPermissionsConfiguration.xcconfig in Source/SPPermissions/Supporting Files, comment unusable permissions and rebuild:

carthage build

Manually

If you prefer not to use any of dependency managers, you can integrate SPPermissions into your project manually. Put Source/SPPermissions folder in your Xcode project. Make sure to enable Copy items if needed and Create groups.

After it need add configuration. See example SPPermissionsConfiguration.xcconfig file or example project. If you don't know how add configuration file, see this short video.

Usage

This project had separate modules for the display UI options. The interfaces are: Dialog, List and Native. Each interface has delegates and a datasource. If you want see an example app, open SPPermissions.xcodeproj and choose the Example target.

Dialog

This is a Modal alert, which was used in the previous version (<5.x). I recomend the use of this alert style when your requested permissions are less than three. Usage example:

let controller = SPPermissions.dialog([.camera, .photoLibrary])

// Ovveride texts in controller
controller.titleText = "Title Text"
controller.headerText = "Header Text"
controller.footerText = "Footer Text"

// Set `DataSource` or `Delegate` if need. 
// By default using project texts and icons.
controller.dataSource = self
controller.delegate = self

// Always use this method for present
controller.present(on: self)

List

Native UITableViewController with support for the iPad. Use it with more than two permissions. An example of how it is used:

let controller = SPPermissions.list([.calendar, .camera, .contacts])

// Ovveride texts in controller
controller.titleText = "Title Text"
controller.headerText = "Header Text"
controller.footerText = "Footer Text"

// Set `DataSource` or `Delegate` if need. 
// By default using project texts and icons.
controller.dataSource = self
controller.delegate = self

// Always use this method for present
controller.present(on: self)

Native

Request permissions with native alerts. You can request many permissions at once:

let controller = SPPermissions.native([.calendar, .camera, .contacts])

// Set `Delegate` if need. 
controller.delegate = self

// Always use this method for request. 
// You can pass any controller, this request because need implement base protocol.
controller.present(on: self)

Permissions

To check the state of any permission, call enum SPPermission:

let state = SPPermission.calendar.isAuthorized

Also available is the func isDenied. This returns false if the permission has not been requested before.

DataSource & Delegate

For a customized permssions view, implement SPPermissionsDataSource:

func configure(_ cell: SPPermissionTableViewCell, for permission: SPPermission) -> SPPermissionTableViewCell {
    return cell
}

Using a delegate, you can customize texts, colors, and icons. For a default view configure with the default values. After configuration return the cell.

You can customize:

// Titles
cell.permissionTitleLabel.text = "Notifications"
cell.permissionDescriptionLabel.text = "Remind about payment to your bank"
cell.button.allowTitle = "Allow"
cell.button.allowedTitle = "Allowed"

// Colors
cell.iconView.color = .systemBlue
cell.button.allowedBackgroundColor = .systemBlue
cell.button.allowTitleColor = .systemBlue

// If you want set custom image.
cell.set(UIImage(named: "IMAGE-NAME")!)

Delegate

In the delegate you can implement these methods:

// Events
func didAllow(permission: SPPermission) {}
func didDenied(permission: SPPermission) {}
func didHide(permissions ids: [Int])

// Denied alert. Show alert if permission denied.
func deniedData(for permission: SPPermission) -> SPPermissionDeniedAlertData?

You can detect permission values as follows:

let permissions = ids.map { SPPermission(rawValue: $0) }

Denied alert

If you don't want show an alert if a permission is denied, return nil in the delegate. You can set the text in the alert:

func deniedData(for permission: SPPermission) -> SPPermissionDeniedAlertData? {
    if permission == .notification {
        let data = SPPermissionDeniedAlertData()
        data.alertOpenSettingsDeniedPermissionTitle = "Permission denied"
        data.alertOpenSettingsDeniedPermissionDescription = "Please, go to Settings and allow permission."
        data.alertOpenSettingsDeniedPermissionButtonTitle = "Settings"
        data.alertOpenSettingsDeniedPermissionCancelTitle = "Cancel"
        return data
    } else {
        // If returned nil, alert will not show.
        return nil
    }
}

If you don't implement this method, the alert will appear with default text. To disable the alert you just need return nil.

Good Practices

I recommend that you show the user all of the permission options, even if some of them are already allowed. But if you want to request only non-allowed permissions, use this code:

let controller = SPPermissions.list([.notification, .reminders].filter { !$0.isAuthorized } )
controller.present(on: self)

A good way to check for the need to show a dialog: check that all permissions are currently authorized by the user:

let permissions = [.notification, .reminders].filter { !$0.isAuthorized }
if permissions.isEmpty {
    // No need show dialog
} else {
    // Show dialog
}

If you request location services, you can show both .locationWhenInUse & .locationAlwaysAndWhenInUse. If the user allowed always mode, they can also change to when in use mode:

let controller = SPPermissions.dialog([.locationWhenInUse, .locationAlwaysAndWhenInUse])
controller.present(on: self)

Keys in Info.plist

You need to add some keys to the Info.plist file with descriptions. List of keys:

  • NSCameraUsageDescription
  • NSContactsUsageDescription
  • NSCalendarsUsageDescription
  • NSMicrophoneUsageDescription
  • NSAppleMusicUsageDescription
  • NSSpeechRecognitionUsageDescription
  • NSMotionUsageDescription
  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysAndWhenInUseUsageDescription
  • NSLocationAlwaysUsageDescription (iOS 10 and earlier)
  • NSBluetoothAlwaysUsageDescription
  • NSBluetoothPeripheralUsageDescription (iOS 12 and earlier)
  • NSUserTrackingUsageDescription

Do not use the description as the name of the key.

Localization keys

If you use xliff localization export, keys will be create automatically. If you prefer do the localization file manually, you need to create InfoPlist.strings, select languages in the right side menu and add keys as keys in plist-file. See:

"NSCameraUsageDescription" = "Here description of usage camera";

Design of previous version

I developed SPPermissions in an 'Apple-way'. To accomplish this, I checked 30 apps to get UI-elements for this project. I then took screenshots and re-drew the elements in Sketch. For example, the project's Allow button is similar to the Get button in the AppStore. Check this timelapse to see how I designed the 4.0 version of SPPermissions:

Timelaps on YouTube

Other Projects

SPAlert

It is popup from Apple Music & Feedback in AppStore. Contains Done & Heart presets. Done present with draw path animation. I clone Apple's alerts as much as possible. You can find this alerts in AppStore after feedback, after added song to library in Apple Music. I am also add alert without icon, as simple message.

SPDiffable

Apple's diffable API requerid models for each object type. If you want use it in many place, you pass many time to implemenet and get over duplicates codes. This project help you do it elegant with shared models and special cell providers for one-usage models.

Russian Community

Присоединяйтесь в телеграм канал Код Воробья, там найдете заметки о iOS разработке и дизайне. Большие туториалы выклыдываю на YouTube.

Tutorials on YouTube

Github

link
Stars: 3970

Dependencies

Used By

Total: 0

Releases

Add logic for Bluetooth request - 2020-07-12 08:50:50

Add example for Tracking permission, but now it commented. With new Xcode it will be available.

Change protect level to public for custom icon - 2020-04-17 22:38:05

Update email - 2020-03-15 21:17:44

Added `bounceAnimationEnabled` - 2020-03-02 16:07:28

Flag allow remove bounce animation when presenting and disable drag gester for dialog view.

Fix bugs when delegate not call for native permissions - 2020-02-11 08:53:51

Add Bluetooth permission - 2019-12-10 19:35:30

In this version you can't request bluetooth, but can check it state. If you know how request bluetooth permission, please, create pull request or send me code.

Fix denied state of location permission - 2019-11-30 18:26:13

Also update readme.

Add permissions list in `didHide` delegate method. - 2019-11-27 23:18:56

And small update docs & readme.

Change data source and delegate. Can customise colours - 2019-11-26 14:32:51

Update data source and delegate. Update readme. Allowed customise colours. Fix layout in dialog view. Update tv example target.

Add tvOS support - 2019-11-25 18:44:41

Add tvOS support. Can install via Cocoapods & SPM. Added example target. Thanks @RomanPodymov for PR #149.

Add `prefersLargeTitles ` - 2019-11-20 18:32:23

Add prefersLargeTitles to list controller. Fix native mode.

Update List interface - 2019-11-20 09:40:56

Add call delegate didHide when List controller dismiss by swipe.

Add new delegate method - 2019-11-19 20:51:00

Add delegate method didHide. Set fix order for permissions.

Fix protect level for permission data - 2019-11-19 15:29:28

Fix bugs in notifications - 2019-11-19 14:33:45

Fix bug with notifications. Update docs. Add alert with go to settings, also allow disable it alert.

Fix bugs - 2019-11-19 08:36:32

Fix protect level for SPPermissionData.

Change files struct - 2019-11-18 09:54:53

Also update error installation message. Update Swift Package Manager file.

New 5.0 version - 2019-11-17 23:19:44

Add List mode. Update data source and delegates, now it need set in controller. Add example video how install manually SPPermissions. Recreate all classes.

Update Readme after renaming - 2019-11-03 19:26:58

Renamed from SPPermission to SPPermissions.

Rename pod - 2019-11-03 19:05:28

Add function `request if need` - 2019-10-31 16:44:16

Allow request only not allowed permissions.

Fix availability `requestIfNeed` func. - 2019-10-31 16:20:34

Add requestIfNeed to source, set public access.

Allow always visible status bar - 2019-09-28 19:40:35

Manage by flags in datasource alwaysVisibleStatusBar. Add func requestIfNeeded, see about it in Readme.

Add example configuration file - 2019-06-15 10:50:03

Fix bug with Carthage - 2019-06-15 06:56:31

Fix Carthage - 2019-06-08 08:39:43

Fix Carthage & update some files.

Separate permissions into modules - 2019-06-04 17:18:59

Due to Apple's new policy regarding permission access you need to specifically define what kind of permissions you want to access using subspecs.

Fix names - 2019-05-25 13:44:31

Fix names of property and functions.

Add property `startTransitionYoffset` - 2019-05-15 16:28:30

Add property startTransitionYoffset. This property allow customise position before start. Set to 0 if need disable wobble animation. Add icon for example project. Update Readme.

Fix bug for denied location permissions. Reload buttons when return to app. - 2019-05-10 14:43:01

Fix bug for denied .locationAlways. Update default text for location permissions. Now reload buttons when user return to app. Update example & Readme.