iOS Xcode File picker and uploading - ios

I am new into this Xcode iOS stuff, I am trying to build a file uploader, you pick a file and then you upload to server. Currently I am stuck at picking the file. I have used some code found on this website, but I am getting some errors.
Class starts like this:
class DocumentsController: UIViewController, UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate
Methods used are:
#objc func pickFile() {
let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF), String(kUTTypePNG), String(kUTTypeJPEG)], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
self.present(importMenu, animated: true, completion: nil)
}
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let myURL = urls.first else {
return
}
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)
}
In the documentPicker method I have two errors:
'URL' is ambiguous for type lookup in this context <- for urls: [URL]
Type of expression is ambiguous without more context <- for guard let myURL = urls.first
If I replace URL with String or NSURL it gets past that, the build is successful, the app on the simulator is running (Iphone 8 plus), I can open the picker, choose a file, but then nothing happens. It just closes the picker and that's it. documentPicker method doesn't trigger. Out of the 4 methods only pickFile and documentMenu are triggering.
Xcode version is 13.3.1

Related

iOS: How to change label "Open" to "Save" in file saving dialog window?

I am not an iOS developer, but I was asked to fix a bug in existing app.
There is a button to save the document from the server to files on the device.
A dialog window appears, you can select a directory and the file will be successfully saved.
But in the dialog window, the label above on the right is “Open”, but should be “Save”.
It is obvious that this is a system window and I can’t just take and change the text, but I saw that in other applications this inscription can be like “Save”
This code fragment is below.
#IBAction func download(_ sender: UIButton) {
let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = .formSheet
present(documentPicker, animated: true, completion: nil)
}
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("documentPicker")
guard controller.documentPickerMode == .open, let url = urls.first else {
print("ERROR")
return
}
guard url.startAccessingSecurityScopedResource() else {
print("failed: startAccessingSecurityScopedResource()")
return
}
if self.downloadUrl.count > 0, self.downloadName.count > 0,
let downloadUrl = URL(string: self.downloadUrl){
// downloading
}
}
I tried to replace ".open" with other options, but it causes a crash.

Delegate method UIDocumentPickerViewController are not working on simulator

Delegate method are not working for UIDocumentPickerViewController
from upload action want to load document from simulator for uploading to other action...
func uploadFile(){
let documentPickerController = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF), String(kUTTypeImage), String(kUTTypeMovie), String(kUTTypeVideo), String(kUTTypePlainText), String(kUTTypeMP3)], in: .import)
documentPickerController.delegate = self
present(documentPickerController, animated: true, completion: nil)
}
On selected didPickDocumentPicker noting happening in swift 5.0
extension UIViewController: UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate
{
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let myURL = urls.first else {
return
}
print("import result : \(myURL)")
let fileName = urls.first?.lastPathComponent
print(fileName)
// self.loadUploadView(selectedFile: fileName!)
}
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)
}
}
For Device its working fine but for simulator its not working
else for iOS versions 13 its not working.
Device Version is 14
Simulator versions is 13.

iOS Swift, what is the url of the "on my iPhone" folder

I need to import to my app some document that have been saved into the "On My iPhone" folder. What would be the url of this folder? (those document (pdf) are saved outside the app by the user and I would like if possible to move/copy them to the app document folder but again I can't find that url.
Try this code (the way to pick needed document from iPhone Folder:
extension YourViewController: UIDocumentInteractionControllerDelegate {
/// If presenting a top a navigation stack, provide the navigation controller in order to animate in a manner consistent with the rest of the platform
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self.navigationController ?? self
}
}
extension YourViewController : UIDocumentPickerDelegate {
func initDocs() {
let pickerController = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
pickerController.delegate = self
if #available(iOS 11.0, *) {
pickerController.allowsMultipleSelection = false
}
present(pickerController, animated: false, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
if let url = urls.first {
self.handleDoc(url: url) // method in your view controller
}
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
print("url = \(url)")
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true, completion: nil)
}
}
In YourViewController call function:
#IBAction func importPem(_ sender: UIButton) {
initDocs()
UIDocumentInteractionController().presentPreview(animated: true)
}

Get file from Url or path?

I have integrated UIDocumentPickerDelegate or UIDocumentMenuDelegate, I have an issue to get the file from URL or DocumentPicker. How can I solve this issue in iOS swift?
You can get file easily like,
If you need to get image
#IBAction func btn_Handler_iCloud(_ sender: Any) {
let doc = UIDocumentMenuViewController(documentTypes: [String(kUTTypeImage)], in: .import)
doc.delegate = self
doc.modalPresentationStyle = .formSheet
self.present(doc, animated: true, completion: nil)
}
func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
let data = try! Data(contentsOf: urls[0])
imageview_Buaty.image = UIImage.init(data: data)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true, completion: nil)
}
Getting document URL or data from UIDocumentPickerViewController:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
// Available from iOS 8.0 to iOS 11.0
self.handleFileSelection(inUrl: url)// Here url is document's URL
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
// Available from iOS 11.0
self.handleFileSelection(inUrl: urls.first!) // Here urls is array of URLs
}
private func handleFileSelection(inUrl:URL) -> Void {
do {
// inUrl is the document's URL
let data = try Data(contentsOf: inUrl) // Getting file data here
} catch {
dLog(message: "document loading error")
}
}

How to open the Document files e.g(.pdf,.doc,.docx) in ios mobile when a button action using swift3.0?

I need to open UIDocumentPickerViewController and It should allow user to select all type of files. ie.(.pdf,.doc)files I used UIDocumentPickerViewController method.
my Code:
UIDocumentPickerDelegate, UIDocumentMenuDelegate in my class declaration
//upload file
func OpenFile(){
let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePNG),String(kUTTypeImage)], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .fullScreen
self.present(importMenu, animated: true, completion: nil)
}
#available(iOS 8.0, *)
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let cico = url as URL
print("The Url is : \(cico)")
do {
let weatherData = try NSData(contentsOf: cico, options: NSData.ReadingOptions())
print(weatherData)
let activityItems = [weatherData]
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
if UI_USER_INTERFACE_IDIOM() == .phone {
self.present(activityController, animated: true, completion: { _ in })
}
else {
let popup = UIPopoverController(contentViewController: activityController)
popup.present(from: CGRect(x: CGFloat(self.view.frame.size.width / 2), y: CGFloat(self.view.frame.size.height / 4), width: CGFloat(0), height: CGFloat(0)), in: self.view, permittedArrowDirections: .any, animated: true)
}
} catch {
print(error)
}
//optional, case PDF -> render
//displayPDFweb.loadRequest(NSURLRequest(url: cico) as URLRequest)
}
#available(iOS 8.0, *)
public func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print(" cancelled by user")
dismiss(animated: true, completion: nil)
}
In this code the app will crash. the reason is Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'You cannot initialize a UIDocumentPickerViewController except by the initWithDocumentTypes:inMode: and initWithURL:inMode: initializers.
I don't know how to initialise the initWithDocumentTypes:inMode. I'm new to iOS any one help me???
can you please help me..
Swift 3*, 4*,
To open document and select any document, you are using UIDocumentPickerViewController then all documents presented in your iCloud, Files and in Google Drive will be shown if Google Drive is connected in user device. Then selected document need to download in your app and from there you can show it in WKWebView,
#IBAction func uploadNewResumeAction(_ sender: Any) {
/* let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import) */
let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.text", "com.apple.iwork.pages.pages", "public.data"], in: .import)
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
extension YourViewController: UIDocumentPickerDelegate{
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let cico = url as URL
print(cico)
print(url)
print(url.lastPathComponent)
print(url.pathExtension)
}
}
Note: If you intend to select all files the you have to use following code:
let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import)
In your action method.
To open the specific document files of (.pdf, .doc, .docx) using UIDocumentPickerViewController in Swift:
documentTypes would be
import import MobileCoreServices
["com.microsoft.word.doc","org.openxmlformats.wordprocessingml.document", kUTTypePDF as String]
Example:
let importMenu = UIDocumentPickerViewController(documentTypes: ["com.microsoft.word.doc","org.openxmlformats.wordprocessingml.document", kUTTypePDF as String], in: UIDocumentPickerMode.import)
importMenu.delegate = self
self.present(importMenu, animated: true, completion: nil)
Actually, instead of WebView you could also use the QuickLook
Framework, which is designed for this specific purpose. You just pass
the location of the file and conform to the protocols. It will present
a view controller with the document inside.
It supports the following file:
- iWork documents (Pages, Numbers and Keynote)
- Microsoft Office documents (as long as they’ve been created with Office 97 or any other newer version)
- PDF files
- Images
- Text files
- Rich-Text Format documents
- Comma-Separated Value files (csv)
Here is a tutorial by APPCODA, that describes the same.
and
Here is the tutorial provided by Apple OBJ-C version.

Resources