How to restrict selecting folder for UIDocumentPickerViewController while multiple select option - ios

I have integrated UIDocumentPickerViewController in application. I can access the files from Files app. Need to restrict folder selection from drive and cloud as well.
When I enable multiple file "Select" option using "allowsMultipleSelection". when user select "Select" option in documentPickerViewController, I don't want to allow user to select folder.
How do I restrict user to select "Folder"?.
Code used to launch Files app is:
let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.data"], in: UIDocumentPickerMode.import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = UIModalPresentationStyle.fullScreen
self.present(documentPicker, animated: true, completion: {
if #available(iOS 11.0, *) {
documentPicker.allowsMultipleSelection = true
} else {
// Fallback on earlier versions
}
})

You can not restrict folder selection however you can ignore selected folder URL.
There will "/" character with end of each folder url, So you can compare it by using below code and skip it.
Swift 4
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    var arrFilesURL = [URL]()
    arrFilesURL = urls.filter { (url) -> Bool in
        return url.absoluteString.last != "/"
    }
    controller.dismiss(animated: true, completion: nil)
}

Related

Check condition for a zip file in UIDocumentPickerViewController

This is my code for calling UIDocumentPickerViewController to choose the files for my firmware update which have to be .zip only. When I press on "Select" button, the Document Picker View shows up:
#IBAction func selectButtonAction(_ sender: UIButton) {
if sender.title(for: .normal) == "Select"{
if let controller = (UIApplication.shared.delegate as? AppDelegate)?.currentViewController {
let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypeArchive)], in: .open )
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
controller.present(importMenu, animated: true, completion: nil)
}
} else {
changeDFUItemsDesign(isFileURLNil: true)
}
}
Right now it's possible to open the files in .docx format, but I need to only let the user pick one format - a zip file.
I cannot present what I have done so far because I am not able to find a solution. Is there a way to make a check for a zip file or just forbid selecting other formats? Thank you!
Intialize the DocumentPicker with the list of supported types.
let zip = ["com.pkware.zip-archive"]
let importMenu = UIDocumentPickerViewController(documentTypes: zip, in: .import)
Here's a list of supported UTIs
In my view's extension I use the UIDocumentPickerDelegate and in the function I check if my file's last component is zip:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
if let fileURL = urls.first, fileURL.pathExtension == "zip" {
self._fileURL = fileURL
self.fileNameLabel.text = _fileURL?.lastPathComponent
} else {
_fileURL = nil
fileNameLabel.text = "Select file"
}
}

By UIImagePickerController we can access and upload images. How to access and upload documents from iphone?

I'm developing a loan related app where user upload his documents like pay-slips, it-returns, etc. For that I should show the user all the documents he/she having in his/her iPhone. How to show a picker for documents?
UIDocumentPickerViewController is what you are looking for.
You init one with a list of document types you want to be able to pick, and a mode, which is usually .open to get access to a file in a cloud provider directly. You can also use .import which will copy the file to your container instead of giving you access to the file in the cloud provider's container directly, if the goal is just to upload it (you can remove the copy after uploading).
Once you have created your picker, you present it, and implement the delegate method didPickDocumentsAt to retrieve the list of files chosen by the user.
Check out the Particles sample code and this years WWDC session « Managing Documents in your iOS Apps »
just call openDocumentPicker method when you want to upload document in your application..
import MobileCoreServices
func openDocumentPicker() {
let importMenu = UIDocumentMenuViewController(documentTypes: [kUTTypePDF as String], in: .import)
importMenu.delegate = self
self.present(importMenu, animated: true, completion: nil)
}
create your viewcontroller extension
extension ViewController: UIDocumentMenuDelegate {
func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentMenuWasCancelled(_ documentMenu: UIDocumentMenuViewController) {
print("we cancelled")
dismiss(animated: true, completion: nil)
}
}
extension ViewController: UIDocumentPickerDelegate {
internal func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: url.path)
let fileSizeNumber = fileAttributes[FileAttributeKey.size] as! NSNumber
let fileSizea = fileSizeNumber.doubleValue
let fileSize = fileSizea/1000000.0
if fileSize > 5.0 {
appDelegate.displayAlert(Title: "", Message: "Selected File are too big,Please select file less than 5.0 mb")
} else {
let documentData = try Data(contentsOf: url, options: .dataReadingMapped)
}
} catch let error {
print(error.localizedDescription)
}
}
}
above this code only you can access pdf if you want to access anpther document than just use this code
/*
let pdf = String(kUTTypePDF)
let spreadsheet = String(kUTTypeSpreadsheet)
let movie = String(kUTTypeMovie)
let aviMovie = String(kUTTypeAVIMovie)
let docs = String(kUTTypeCompositeContent)
let img = String(kUTTypeImage)
let png = String(kUTTypePNG)
let jpeg = String(kUTTypeJPEG)
let txt = String(kUTTypeText)
let zip = String(kUTTypeZipArchive)
let msg1 = String(kUTTypeEmailMessage)
let msg2 = String(kUTTypeMessage)
let types = [pdf, spreadsheet, movie, aviMovie, img, png, jpeg, txt, docs, zip, msg1, msg2]
*/
iOS 11 or later
let importMenu = UIDocumentPickerViewController.init(documentTypes: ["public.item"], in: UIDocumentPickerMode.import)
self.present(importMenu, animated: true) {
}
Please Refer the following link for more description
https://www.techotopia.com/index.php/An_iOS_Document_Browser_Tutorial
iOS 10 or earlier
You can write the below function when your document picker opens. it will work for all the file types which you want to upload.
func openDocumentPicker() {
let importMenu = UIDocumentMenuViewController(documentTypes: ["public.item"], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
self.present(importMenu, animated: true, completion: nil)
}

which is this controller in iOS

I was surfing some site in safari. it was attachment button. when I clicked on that button. it showed this controller. Can any1 tell me which is this default functionality safari provide. it is dere in various apps too like slack.
its shows icloud/google drive/dropbox all three in one action.
It is UIDocumentPickController. Check the apple developer documentation
let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], in: UIDocumentPickerMode.import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = UIModalPresentationStyle.formSheet
self.present(documentPicker, animated: true, completion: nil)
And delegate
// MARK: - UIDocumentPickerDelegate Methods
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
if controller.documentPickerMode == UIDocumentPickerMode.import {
// This is what it should be
// self.newNoteBody.text = String(contentsOfFile: url.path!)
}
}
After adding the code you should check this post too or else you will get an exception. You should go to capabilities & turn iCloud capabilities on. Add icloud containers also there
UIDocumentMenuController is the same as UIDocumentPickerViewController. But its deprecated. check the developer documentation here

UIDocumentMenuViewController blank Options

I have a problem with iCloud file import
I'm getting empty options after I choose the place to import from (iCloud, google drive, dropbox ... etc)
I have data on iCloud drive and the entitlements are right
So what is wrong with this code or is there anything about the settings may cause this problem?
here is the code
#IBAction func selectionButtonAction(_ sender: Any) {
let types = [kUTTypePDF as String ,kUTTypePNG as String, kUTTypeImage as String,kUTTypeJPEG as String]
UINavigationBar.appearance().isTranslucent = true
let documentMenu = UIDocumentMenuViewController(documentTypes: types, in: .import)
documentMenu.delegate = self
self.viewController?.present(documentMenu, animated: true, completion: nil)
}
func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentMenu.delegate = self
self.viewController?.present(documentMenu, animated: true, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
if controller.documentPickerMode == .import {
// do staff
}
}
Here is what I get When I run the app on iOS 10
When I Press choose File
then after pressing on iCloud
That's what I get if I run the app on iOS 9:
I'm sure I have data there like here in the iCloud Drive application
And the entitlement
I had the same problem, when trying to present a already used Instance of the UIDocumentMenuViewController.
I was instantiating it lazily like this:
lazy var documentMenuController: UIDocumentMenuViewController = {
let controller = UIDocumentMenuViewController(documentTypes: ["com.adobe.pdf"], in: .import)
controller.delegate = self
return controller
}()
Which produced this error every time except the first time.
So I changed the code to this:
var documentMenuController: UIDocumentMenuViewController {
let controller = UIDocumentMenuViewController(documentTypes: ["com.adobe.pdf"], in: .import)
controller.delegate = self
return controller
}
To obtain a fresh instance on every access of the property.

How to access Cloud drives to import files to my app in swift?

I want to get documents from Cloud services like iCloud , google drive and dropbox on a button click (like in WhatsApp screenshot below), does anyone know how to do it in swift ? Thanks in advance
From your project's capabilities. First enable both the iCloud services and the Key-Sharing, import MobileCoreServices in your class and finally extended the following three classes inside your UIViewController :
UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate
Implement the following functions :
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let myURL = url as URL
print("import result : /(myURL)")
}
public func documentMenu(_ documentMenu:UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("view was cancelled")
dismiss(animated: true, completion: nil)
}
How to call all of this? Add the following bit of code to your click function..
func clickFunction(){
let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
self.present(importMenu, animated: true, completion: nil)
}
Click your button. The following menu will pop up ..
In the case of DropBox. Upon clicking on any item. You will be redirected back to your app and the URL will be logged in your terminal.
Manipulate the documentTypes to your need. In my app, Users permitted to Pdf only. So, suit yourself.
kUTTypePDF
Also if you feel like customizing your own menu bar. Add the following code and customize your own function inside the handler
importMenu.addOption(withTitle: "Create New Document", image: nil, order: .first, handler: { print("New Doc Requested") })
Enjoy it.
First enable iCloud documents Capabilitie, see Apple documentation here
The you have to use UIDocumentMenuViewController
let importMenu = UIDocumentMenuViewController(documentTypes: doctypes, inMode: .Import)
importMenu.delegate = self
importMenu.popoverPresentationController?.barButtonItem = self.addButon;
self.presentViewController(importMenu, animated: true, completion: nil)

Resources