Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Permission handling in image picker #334

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
20 changes: 20 additions & 0 deletions BSImagePicker.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
objects = {

/* Begin PBXBuildFile section */
2F0FADE226668A74005747B4 /* AutoLayout+BSImagePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0FADE126668A74005747B4 /* AutoLayout+BSImagePicker.swift */; };
2F0FADE526669B0F005747B4 /* Size+BSImagePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0FADE426669B0F005747B4 /* Size+BSImagePicker.swift */; };
2F0FADE826669B3C005747B4 /* AutorizationStatusHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0FADE726669B3C005747B4 /* AutorizationStatusHeaderView.swift */; };
2F0FADEC2666A140005747B4 /* Alert+BSImagePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0FADEB2666A140005747B4 /* Alert+BSImagePicker.swift */; };
2F0FADEF2666A185005747B4 /* PHAuthorization+BSImagePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0FADEE2666A185005747B4 /* PHAuthorization+BSImagePicker.swift */; };
531D8C532249C81A00281681 /* SettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 531D8C522249C81A00281681 /* SettingsTests.swift */; };
53FEDA162247FEB80098E34A /* CGSize+Scale.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53FEDA152247FEB80098E34A /* CGSize+Scale.swift */; };
53FEDA18224805BA0098E34A /* CGSizeExtensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53FEDA17224805BA0098E34A /* CGSizeExtensionTests.swift */; };
Expand Down Expand Up @@ -78,6 +83,11 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
2F0FADE126668A74005747B4 /* AutoLayout+BSImagePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AutoLayout+BSImagePicker.swift"; sourceTree = "<group>"; };
2F0FADE426669B0F005747B4 /* Size+BSImagePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Size+BSImagePicker.swift"; sourceTree = "<group>"; };
2F0FADE726669B3C005747B4 /* AutorizationStatusHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutorizationStatusHeaderView.swift; sourceTree = "<group>"; };
2F0FADEB2666A140005747B4 /* Alert+BSImagePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Alert+BSImagePicker.swift"; sourceTree = "<group>"; };
2F0FADEE2666A185005747B4 /* PHAuthorization+BSImagePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PHAuthorization+BSImagePicker.swift"; sourceTree = "<group>"; };
531D8C522249C81A00281681 /* SettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsTests.swift; sourceTree = "<group>"; };
53FEDA152247FEB80098E34A /* CGSize+Scale.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CGSize+Scale.swift"; sourceTree = "<group>"; };
53FEDA17224805BA0098E34A /* CGSizeExtensionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CGSizeExtensionTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -222,6 +232,7 @@
C2DC13C923F75BDA0035FD13 /* NumberView.swift */,
55BCF8C521D52C1000386752 /* CameraCollectionViewCell.swift */,
55F67B7A222F088500805134 /* GradientView.swift */,
2F0FADE726669B3C005747B4 /* AutorizationStatusHeaderView.swift */,
);
path = Assets;
sourceTree = "<group>";
Expand Down Expand Up @@ -337,6 +348,10 @@
isa = PBXGroup;
children = (
94DA686F247BDE5900CD5251 /* UIColor+BSImagePicker.swift */,
2F0FADE126668A74005747B4 /* AutoLayout+BSImagePicker.swift */,
2F0FADE426669B0F005747B4 /* Size+BSImagePicker.swift */,
2F0FADEB2666A140005747B4 /* Alert+BSImagePicker.swift */,
2F0FADEE2666A185005747B4 /* PHAuthorization+BSImagePicker.swift */,
);
path = Extension;
sourceTree = "<group>";
Expand Down Expand Up @@ -462,6 +477,8 @@
550CB425230FD01200543217 /* ImageView.swift in Sources */,
55BCF8D521D52C1000386752 /* AssetCollectionViewCell.swift in Sources */,
559DB81B21E6B43400CD58B4 /* ImagePickerController+ButtonActions.swift in Sources */,
2F0FADEC2666A140005747B4 /* Alert+BSImagePicker.swift in Sources */,
2F0FADE226668A74005747B4 /* AutoLayout+BSImagePicker.swift in Sources */,
559DB81121E6561300CD58B4 /* ImagePickerController+Closure.swift in Sources */,
55C5B802222BD529003CF3F1 /* DropdownPresentationController.swift in Sources */,
55BCF8E021D52C1000386752 /* ZoomAnimator.swift in Sources */,
Expand All @@ -471,11 +488,13 @@
94DA6870247BDE5900CD5251 /* UIColor+BSImagePicker.swift in Sources */,
5554729D21E5248400B90CA5 /* ImagePickerController.swift in Sources */,
55C5B800222BD445003CF3F1 /* DropdownTransitionDelegate.swift in Sources */,
2F0FADE526669B0F005747B4 /* Size+BSImagePicker.swift in Sources */,
55BCF8D321D52C1000386752 /* AssetsCollectionViewDataSource.swift in Sources */,
550CB427230FD08200543217 /* ImageViewLayout.swift in Sources */,
55BCF8D621D52C1000386752 /* AlbumCell.swift in Sources */,
55BCF8D021D52C1000386752 /* AlbumsTableViewDataSource.swift in Sources */,
55F67B77222EEB2500805134 /* VideoCollectionViewCell.swift in Sources */,
2F0FADE826669B3C005747B4 /* AutorizationStatusHeaderView.swift in Sources */,
559DB80F21E655D000CD58B4 /* ImagePickerControllerDelegate.swift in Sources */,
559DB81721E6AFD800CD58B4 /* ImagePickerController+Assets.swift in Sources */,
55CDB45B223435420050D572 /* PlayerView.swift in Sources */,
Expand All @@ -485,6 +504,7 @@
55BCF8D721D52C1000386752 /* CheckmarkView.swift in Sources */,
555472AE21E538B000B90CA5 /* AssetsViewController.swift in Sources */,
5543942D232A4EB500DB51B7 /* LivePreviewViewController.swift in Sources */,
2F0FADEF2666A185005747B4 /* PHAuthorization+BSImagePicker.swift in Sources */,
C2DC13CA23F75BDB0035FD13 /* NumberView.swift in Sources */,
55BCF8DC21D52C1000386752 /* PreviewViewController.swift in Sources */,
55BCF8CF21D52C1000386752 /* Settings.swift in Sources */,
Expand Down
8 changes: 4 additions & 4 deletions Example.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -432,14 +432,14 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = Y2NHS7RD78;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should not be present in the PR

Copy link
Author

@mithilesh-parmar mithilesh-parmar Dec 19, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

replaced with original

DEVELOPMENT_TEAM = F85Q68998X;
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = Example/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = se.backslashed.Example;
PRODUCT_BUNDLE_IDENTIFIER = se.backslashed.Example.mithilesh;
PRODUCT_NAME = ImagePicker;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
Expand All @@ -451,14 +451,14 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = Y2NHS7RD78;
DEVELOPMENT_TEAM = F85Q68998X;
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = Example/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = se.backslashed.Example;
PRODUCT_BUNDLE_IDENTIFIER = se.backslashed.Example.mithilesh;
PRODUCT_NAME = ImagePicker;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
Expand Down
44 changes: 40 additions & 4 deletions Example/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class ViewController: UIViewController {
return 2
}
}

self.presentImagePicker(imagePicker, select: { (asset) in
print("Selected: \(asset)")
}, deselect: { (asset) in
Expand All @@ -91,16 +91,17 @@ class ViewController: UIViewController {
@IBAction func showImagePickerWithSelectedAssets(_ sender: UIButton) {
let allAssets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
var evenAssets = [PHAsset]()

allAssets.enumerateObjects({ (asset, idx, stop) -> Void in
if idx % 2 == 0 {
evenAssets.append(asset)
}
})

let imagePicker = ImagePickerController(selectedAssets: evenAssets)
imagePicker.settings.fetch.assets.supportedMediaTypes = [.image]



self.presentImagePicker(imagePicker, select: { (asset) in
print("Selected: \(asset)")
}, deselect: { (asset) in
Expand All @@ -111,5 +112,40 @@ class ViewController: UIViewController {
print("Finished with selections: \(assets)")
})
}

func showImagePickerWithPermissionHandling() {
let imagePicker = ImagePickerController()
imagePicker.settings.selection.max = 5
imagePicker.settings.theme.selectionStyle = .numbered
imagePicker.settings.fetch.assets.supportedMediaTypes = [.image, .video]
imagePicker.settings.selection.unselectOnReachingMax = true
imagePicker.settings.permission.enabled = true

imagePicker.imagePickerDelegate = self
self.present(imagePicker, animated: true, completion: nil)
}

}


extension ViewController: ImagePickerControllerDelegate {
func imagePicker(_ imagePicker: ImagePickerController, didSelectAsset asset: PHAsset) {
print("Selected: \(asset)")
}

func imagePicker(_ imagePicker: ImagePickerController, didDeselectAsset asset: PHAsset) {
print("Deselected: \(asset)")
}

func imagePicker(_ imagePicker: ImagePickerController, didFinishWithAssets assets: [PHAsset]) {
print("Finished with selections: \(assets)")
}

func imagePicker(_ imagePicker: ImagePickerController, didCancelWithAssets assets: [PHAsset]) {
print("Canceled with selections: \(assets)")
}

func imagePicker(_ imagePicker: ImagePickerController, didReachSelectionLimit count: Int) {

}
}
3 changes: 3 additions & 0 deletions Sources/Controller/ImagePickerController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import Photos
@objcMembers open class ImagePickerController: UINavigationController {
// MARK: Public properties
public weak var imagePickerDelegate: ImagePickerControllerDelegate?

public var settings: Settings = Settings()
public var doneButton: UIBarButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)
public var cancelButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
Expand All @@ -47,6 +48,7 @@ import Photos
var onDeselection: ((_ asset: PHAsset) -> Void)?
var onCancel: ((_ assets: [PHAsset]) -> Void)?
var onFinish: ((_ assets: [PHAsset]) -> Void)?
var onPermissionChange: ((_ status: PHAuthorizationStatus) -> Void)?
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not used anywhere

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed onPermissionChange


let assetsViewController: AssetsViewController
let albumsViewController = AlbumsViewController()
Expand Down Expand Up @@ -93,6 +95,7 @@ import Photos
// Setup view controllers
albumsViewController.delegate = self
assetsViewController.delegate = self


viewControllers = [assetsViewController]
view.backgroundColor = settings.theme.backgroundColor
Expand Down
2 changes: 2 additions & 0 deletions Sources/Controller/ImagePickerControllerDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,6 @@ public protocol ImagePickerControllerDelegate: class {
/// - Parameter imagePicker: The image picker that selection limit was reached in.
/// - Parameter count: Number of selected assets.
func imagePicker(_ imagePicker: ImagePickerController, didReachSelectionLimit count: Int)

}

83 changes: 83 additions & 0 deletions Sources/Extension/Alert+BSImagePicker.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 Mithilesh Parmar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import UIKit
import Photos

extension AssetsViewController {
internal func handleDeniedAccess(){
let alert = UIAlertController(title: "Allow access to your photos",
message: "This lets you share from your camera roll and enables other features for photos. Go to your settings and tap \"Photos\".",
preferredStyle: .alert)

let notNowAction = UIAlertAction(title: "Not Now",
style: .cancel,
handler: nil)
alert.addAction(notNowAction)

let openSettingsAction = UIAlertAction(title: "Open Settings",
style: .default) { [unowned self] (_) in
// Open app privacy settings
gotoAppPrivacySettings()
}
alert.addAction(openSettingsAction)
present(alert, animated: true, completion: nil)
}

internal func handleLimitedAccess(){
let actionSheet = UIAlertController(title: "",
message: "Select more photos or go to Settings to allow access to all photos.",
preferredStyle: .actionSheet)

let selectPhotosAction = UIAlertAction(title: "Select more photos",
style: .default) { [unowned self] (_) in
// Show limited library picker
if #available(iOS 14, *) {
PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: self)
}
}
actionSheet.addAction(selectPhotosAction)

let allowFullAccessAction = UIAlertAction(title: "Allow access to all photos",
style: .default) { [unowned self] (_) in
// Open app privacy settings
self.gotoAppPrivacySettings()
}
actionSheet.addAction(allowFullAccessAction)

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheet.addAction(cancelAction)

present(actionSheet, animated: true, completion: nil)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get crash on iPad because the popoverPresentationController?.sourceView is not set. Send here the "manage" button so sheet is displayed properly


}

internal func gotoAppPrivacySettings() {
guard let url = URL(string: UIApplication.openSettingsURLString),
UIApplication.shared.canOpenURL(url) else {
assertionFailure("Not able to open App privacy settings")
return
}

UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
53 changes: 53 additions & 0 deletions Sources/Extension/AutoLayout+BSImagePicker.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 Mithilesh Parmar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import Foundation


@propertyWrapper
public struct UsesAutoLayout<T: UIView> {
public var wrappedValue: T {
didSet {
wrappedValue.translatesAutoresizingMaskIntoConstraints = false
}
}

public init(wrappedValue: T) {
self.wrappedValue = wrappedValue
wrappedValue.translatesAutoresizingMaskIntoConstraints = false
}
}


@propertyWrapper
public struct HasUserInteraction<T: UIView> {
public var wrappedValue: T {
didSet {
wrappedValue.isUserInteractionEnabled = true
}
}

public init(wrappedValue: T) {
self.wrappedValue = wrappedValue
wrappedValue.isUserInteractionEnabled = true
}
}
49 changes: 49 additions & 0 deletions Sources/Extension/PHAuthorization+BSImagePicker.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// The MIT License (MIT)
//
// Copyright (c) 2021 Mithilesh Parmar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import UIKit
import Photos


extension AssetsViewController {

internal func checkAuthorizationStatus(){

if #available(iOS 14, *) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requestAuthorization is done on controller presentation, does nothing here. Should be replaced with the authorizationStatus

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed this method

PHPhotoLibrary.requestAuthorization(for: .readWrite) { [unowned self] (status) in
DispatchQueue.main.async {
self.dataSource.setStatus(status)
self.collectionView.reloadData()
}
}
}else{
PHPhotoLibrary.requestAuthorization { (status) in
DispatchQueue.main.async {
self.dataSource.setStatus(status)
self.collectionView.reloadData()
}
}

}
}

}
Loading