My app is now sharing Documents directory on iOS 11 Files app "On My iPhone" section.
(Thanks to this article: Working with the Files App in iOS 11)
Question is how to open this directory or at least File app root page via URL Scheme. UIDocumentPickerViewController or UIDocumentBrowserViewController doesn't help in this situation.
guard let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
let components = NSURLComponents(url: documentDirectory, resolvingAgainstBaseURL: true) else {
return
}
components.scheme = "shareddocuments"
if let sharedDocuments = components.url {
UIApplication.shared.open(
sharedDocuments,
options: [:],
completionHandler: nil
)
}
The Files app can be opened with the URL scheme shareddocuments://.
I don’t know if there’s a way to open a specific directory however.
func openSharedFilesApp() {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let sharedurl = documentsUrl.absoluteString.replacingOccurrences(of: "file://", with: "shareddocuments://")
print(sharedurl)
let furl:URL = URL(string: sharedurl)!
UIApplication.shared.open(furl, options: [:], completionHandler: nil)
}
This code would work.
Related
This question already has answers here:
How to write a file to a folder located at Apple's Files App in Swift
(2 answers)
Closed 3 years ago.
I am doing a scanner app that scans a picture and converts it into a PDF. I want to be able to save it to "On My IPhone" but I do not know that path URL. Here is what I have so far:
let data = pdfDocument.dataRepresentation()
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let currentTimeStamp = String(Int(NSDate().timeIntervalSince1970))
let docURL = documentsDirectoryURL.appendingPathComponent("Scan\(currentTimeStamp).pdf")
do{
try data?.write(to: docURL)
}catch(let error)
{
print("error is \(error.localizedDescription)")
}
However, the I cannot find my file on my phone because I do not know what "Directory" URL is. How can I get my PDF to save to my iPhone Storage? What is the URL to my "On My IPhone" folder?
Thanks in advance.
In order to retrieve the urls of the files contained in documents directory, you can use the following code snippet.
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents)
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
Just like browsing UIIMage using UIImagePickerViewController. Is there any way to browse Another files in Swift / objective code?
if let fileURL = NSBundle.mainBundle().URLForResource("MyImage", withExtension: "jpg") {
// Instantiate the interaction controller
self.docController = UIDocumentInteractionController(URL: fileURL)
}
else {
shareButton.enabled = false
print("File missing! Button has been disabled")
}
You can only access files in document folder. To access All the files
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
and if you want to single file look following code:
// Get the document directory url
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
print(directoryContents)
// if you want to filter the directory contents you can do like this:
let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
print("mp3 urls:",mp3Files)
let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
print("mp3 list:", mp3FileNames)
} catch {
print(error.localizedDescription)
}
If you want to view PDF files within your app there are two ways.
PDFView - available iOS 11.0
let pdfDocument = PDFDocument(url: url)
pdfView.document = pdfDocument
WKWebView - available iOS 8.0
webView.loadRequest(URLRequest.init(url: url))
You could also use UIWebview to get the same result, But it has been deprecated.
Alternatively, use a file explorer library that you can customize to what you need done. Something like this
https://developer.apple.com/documentation/pdfkit/pdfview
https://developer.apple.com/documentation/webkit/wkwebview
I am designing a webview app in ios. I started making change in my code. And the code change is perfectly alright. The app is responding in simulator(iPhone 7) as it should respond. But when I deploy the app to device(iPhone 7) the app only displays blank page.
It is weird. I read many articles where they were talking about network carrier. Currently it is showing No Service. I tried re-inserting the sim card. But it was of no use. I dont know if that was of any use or not.
If someone could tell what all should I try to debug this out.
Question Update
How I am loading webview
Case 1: When I take the index.html from softlink in project directory then I am able to do it in my device
func getLandingPage() -> URLRequest {
let path = Bundle.main.path(forResource: "www", ofType: nil)!
let url = URL(fileURLWithPath: "\(path)/index.html")
return URLRequest(url: url)
}
URL created- "file:///var/containers/Bundle/Application/9890F84F-4CF4-48AB-8874-AC1BC0B77C55/ios.app/www/index.html"
case 2: When I copy all the files from my softlink directory to directory inside documentDirectory of device and then if I try to load index.html from there then it displaying blank page. And I want this to happen correctly.
func getLandingPage() -> URLRequest {
let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let pathData = "\(docURL[0].path)/\(CODE_FOLDER)/index.html"
let url = URL(fileURLWithPath: pathData)
return URLRequest(url: url)
}
URL create- "file:///var/mobile/Containers/Data/Application/427943C3-2238-49A3-AFCC-5561062B7CDA/Documents/CODE/index.html"
Try to check that URL through this if its opening or not on a button tap to debug weather its working fine or not in device in your condition.
guard let url = URL(string: "your url string/ path") // or directly your URL
else { return }
if UIApplication.shared.canOpenURL(url)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
else
{
print("This doesn't seem to be a valid URL")
}
You can also try this out as documents directory on simulator is different from the real device:
let documentDirUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) // give your url here
let indexFileUrl = documentDirUrl.appendingPathComponent("index.html") // then append the path component of your html file
webView.loadFileURL(indexFileUrl, allowingReadAccessTo: documentDirUrl) // load the webview
Maybe try this one for local folders. You can check if your is File exit or not.
func getLandingPage() -> URLRequest {
let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = "\(CODE_FOLDER)/index.html"
let url = documentURL.appendingPathComponent(path)
if FileManager.default.fileExists(atPath: (url?.path)!) {
return URLRequest(url: url)
} else {
print("File doesn't exists")
}
}
I am trying to download one text file from the server and I have completed it.
Also, I have stored that file but it seems like it stores at some private location and not able to access that file from other file explorer.
Heres the code for it:
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
// let destinationUrl = documentsUrl!.appendingPathComponent("10xFile.pdf")
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent("10xFile.pdf")
let dataFromURL = NSData(contentsOf: location)
dataFromURL?.write(to: fileURL as! URL, atomically: true)
} catch {
print(error)
}
But I need to access this file very easily by any other file explore.
Thanks in advance
Actually as I commented - the feature of iOS - every app has completely separated filesystem sandbox, and one app can't access files of any another app without special permission created by another app.
But you can use UIActivityViewController to pass your pdf files to another app that can render your pdfs.
You can launch UIActivityViewController and pass your pdf file to it. In UIActivityViewController you can choose options - copy file or open in any of apps that can handle pdf file, for example FileManager app.
Here is the code sample somewhere based on code you provided in question, I created UIButton and added IBAction for it - UIActivityViewController is presented when user tap button.
override func viewDidLoad() {
super.viewDidLoad()
do {
let documentDirectory = getDocumentsDirectory()
let fileURL = documentDirectory.appendingPathComponent("10xFile.pdf")
let dataFromURL = try Data(contentsOf: location!)
try dataFromURL.write(to: fileURL, options: [])
} catch {
print(error)
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
#IBAction func actionButtonPressed(_ sender: Any) {
let documentsDir = getDocumentsDirectory()
let fileURL = documentsDir.appendingPathComponent("10xFile.pdf")
let ac = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
self.present(ac, animated: true)
}
My app is now sharing Documents directory on iOS 11 Files app "On My iPhone" section.
(Thanks to this article: Working with the Files App in iOS 11)
Question is how to open this directory or at least File app root page via URL Scheme. UIDocumentPickerViewController or UIDocumentBrowserViewController doesn't help in this situation.
guard let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
let components = NSURLComponents(url: documentDirectory, resolvingAgainstBaseURL: true) else {
return
}
components.scheme = "shareddocuments"
if let sharedDocuments = components.url {
UIApplication.shared.open(
sharedDocuments,
options: [:],
completionHandler: nil
)
}
The Files app can be opened with the URL scheme shareddocuments://.
I don’t know if there’s a way to open a specific directory however.
func openSharedFilesApp() {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let sharedurl = documentsUrl.absoluteString.replacingOccurrences(of: "file://", with: "shareddocuments://")
print(sharedurl)
let furl:URL = URL(string: sharedurl)!
UIApplication.shared.open(furl, options: [:], completionHandler: nil)
}
This code would work.