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")
}
}
Related
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.
I'm working on an iOS application. In the app, I am using Alamofire to create a POST request that returns a raw PDF file in response. Right now, I am able to save the file and open it with UIDocumentInteractionController. But, I want the file to stay in User's documents folder.
Here's how I create the destination path:
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("Dividend Summary Report.pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Someone please tell me what's wrong with my logic and what I can do to correct it.
Well you need to check the file status if it exists then read from documentDirectory else download the file.
Create function like this:
func checkIfFileExists(urlString: String) {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let fileName = urlString
let fileManager = FileManager.default
let filePath = url.appendingPathComponent("\(fileName).pdf")?.path
print("filePath : \(String(describing: filePath))")
if fileManager.fileExists(atPath: filePath!) {
print("File exists")
} else {
print("File doesn't exists")
// set your download function here
}
}
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.
I am having problem with download pdf, saving to document directory and loading it in web view.
I have no experience with download things, saving things to directories and UIWebView before.
Before I ask this question, I've search multiple StackOverflow question and tried my best but it still doesn't work.
First This is how I download the PDF from url and save it to document directory
let myURL = URL(string: "https://example/example/product.pdf")
let urlRequest = NSURLRequest(url: myURL!)
do {
let theData = try NSURLConnection.sendSynchronousRequest(urlRequest as URLRequest, returning: nil)
var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last as? NSURL
docURL = docURL?.appendingPathComponent("my.pdf") as NSURL?
try theData.write(to: docURL as! URL)
print("downloaded")
} catch (let writeError) {
print("error : \(writeError)")
}
The application pauses for a while and prints "downloaded"
This is how I check the list of contacts in my document directory
let docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last)
do{
let contents = try (FileManager.default.contentsOfDirectory(at: docURL!, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles))
print("There are")
print(contents)
}
catch (let error)
{
print("error contents \(error)")
}
It prints "There are [file:///private/var/mobile/Containers/Data/Application/DF6A310C-EB7E-405E-9B1B-654486B5D03A/Documents/my.pdf]"
This is how I load the pdf into webView
var webView = UIWebView(frame : vc.view.frame)
webView.scalesPageToFit = true
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
var documentsDirectory = paths[0]
var filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("my.pdf").absoluteString
var targetURL = URL(fileURLWithPath: filePath)
var request = URLRequest(url: targetURL)
webView.loadRequest(request)
vc.view.addSubview(webView)
The WebView comes up but shows nothing. I'm really confused if my.pdf is really saved with readable PDF format.
I don't know if there are some stuffs like I have to add something in info.plist or enable something in app capabilities. Thank you very much.
I didn't look through all of the code but the following two lines are a problem:
var filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("my.pdf").absoluteString
var targetURL = URL(fileURLWithPath: filePath)
The value of URL absoluteString does not give you a file path so the value of filePath is not a valid value for the URL fileURLWithPath: initializer.
And what's the point of going from URL to String (as a path) and back to a URL? Simply combine those two lines into:
var targetURL = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("my.pdf")
As a side note, use some consistency. In other code you get the Documents folder URL using:
let docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last)
and in other code you use:
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
var documentsDirectory = paths[0]
var ... = URL(fileURLWithPath: documentsDirectory)...
Pick one approach and use it consistently. Since you need a URL, use the first approach. This means the code I suggested should now be:
let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
let targetURL = docURL.appendingPathComponent("my.pdf")