I have download file and saved it into application memory
/Users/MYName/Library/Developer/CoreSimulator/Devices/EDE3E3-E3E5-444C-B04F-6F8F971F2739/data/Containers/Data/Application/6A7D0012-9ACC-4383-BDBA-A98B89018C8C/Library/Caches/CreatedURLDirectory/sample.pdf
How to load Caches/MyDictionaryCreated -> sample.pdf on WKWebView.
*if let url = URL(string: url.path) {
DispatchQueue.main.async {
let request = URLRequest(url: url)
self.webView.load(request)
self.webView.isHidden = false
}
}*
Above url is my file path...
But I know this is not proper way to load
If you want to load a local file into web view you should use loadFileURL instead, for example:
let url = URL(fileURLWithPath: pathToYourFile)
webView.loadFileURL(url, allowingReadAccessTo: url)
Related
I am trying to load PDF from URL using WKWebiew using following code and I have also added necessary delegate methods of WKWebiew.
func loadPDFDocument()
{
if let url = URL(string: self.contentURL)
{
print("URL: \(url)")
if UIApplication.shared.canOpenURL(url) {
self.webView.navigationDelegate = self
self.webView.load(URLRequest(url: url))
} else {
self.showInvalidURLError()
}
} else {
self.showInvalidURLError()
}
}
It is loading but actual content is not showing up, instead it shows like following image:
Now, I have tried it with PDFKit using following code and it is loading the actual content.
func loadPDFDocument()
{
let pdfView = self.createPdfView(withFrame: self.view.bounds)
if let pdfDocument = self.createPdfDocument() {
self.view.addSubview(pdfView)
pdfView.document = pdfDocument
}
}
func createPdfDocument() -> PDFDocument?
{
if let resourceUrl = URL(string: "https://d1shcqlf263trc.cloudfront.net/Engage/Contents/LearningStore/16335111672611633500529010123TestPDFfile06Oct2021.pdf") {
return PDFDocument(url: resourceUrl)
}
return nil
}
func createPdfView(withFrame frame: CGRect) -> PDFView
{
let pdfView = PDFView(frame: frame)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pdfView.autoScales = true
return pdfView
}
The reasons why I want to load this PDF using WKWebiew are following:
I can get callback once URL did finish loading (with or without error)
I also need to load other types of content e.g. PPT, so I can reuse WKWebiew code.
What may be the issue due to which that PDF is not being able to load using WKWebiew. Is that issue with PDF, or with URL or the way I load it with WKWebiew?
The code you have provided directly does not work, and leads to the following error
WebPageProxy::didFailProvisionalLoadForFrame: frameID=3, domain=WebKitErrorDomain, code=102
I did not find any official apple documentation for this specific error but a simple search points to some kind of interruption.
As an alternative, you can try to load data from the URL:
if let data = try? Data(contentsOf: url) {
self.webView.load(data, mimeType: "", characterEncodingName: "", baseURL: url)
}
But this leads to the weird page you have shown in your question.
Here, the web view does not know that you are trying to show a PDF. Simply providing the content type fixes the issue.
if let data = try? Data(contentsOf: url) {
self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "UTF8", baseURL: url)
}
So, you need to make sure the web view knows what type of content you're going to load.
How you would do that for various file types you want to support is a different question you need to figure out.
On application launch i am loading https://www.google.com in WKWebView.
App has one button, on click of that button app is loading local html page from document directory.
i used following code to load html page.
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true)[0]
let fileName = "Demo.html"
let fullDestPath = URL(fileURLWithPath: destPath)
.appendingPathComponent(fileName)
self.webView! .loadFileURL(fullDestPath, allowingReadAccessTo: fullDestPath)
The code was working till iOS 12.1.4 however in iOS 12.2 it is not loading html page and throwing error
ProvisionalPageProxy::didFailProvisionalLoadForFrame: pageID = 1, frameID = 1, navigationID = 2
Check if the file Demo.html is present in the document directory. If is not present, then it will not load html page.
Try to load from Bundle
if let path = Bundle.main.path(forResource: "Demo", ofType: "html") {
let htmlURL = URL(fileURLWithPath: path)
webView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL)
} else {
print("File not found")
}
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 locate a URL which is only pure .m4a sound with my application. I have the URL to the audio and theoretically download it. Then, with the downloaded fileURL to the sound, I try to play it with the AVAudioPlayer, yet it does not play any sound. Here is my code:
In the URL retrieval function, I call: (urls defined as a URL(string: url), url being the retrieve URL string)
downloadSound(url: urls!)
Here is my downloadSound() function:
func downloadSound(url:URL){
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URL, response, error) -> Void in
self?.playSound(url: URL!)
})
downloadTask.resume()
}
And lastly the playSound function:
func playSound(url:URL) {
print("The url is \(url)")
let player = try! AVAudioPlayer(contentsOf: url)
player.play()
Everything is being called as the print("The url is \(url)") returns me the path of the file (I am not actually able to track the file, however).
Here is the general path of the sound on the simulator:
file:///Users/[...]/Library/Developer/CoreSimulator/Devices/116C311A-C7F3-44EC-9762-2FAA0F9FE966/data/Containers/Data/Application/60BFCDE7-AC02-4196-8D1A-24EC646C4622/tmp/CFNetworkDownload_7VDpsV.tmp
Whereas running it on a phone returns:
file:///private/var/mobile/Containers/Data/Application/C75C1F1D-77E9-4795-9A38-3F0756D30547/tmp/CFNetworkDownload_T1XlPb.tmp
Thank you in advance.
I had the same problem and I choosed an alternative solution as app doc said:
A file URL for the temporary file. Because the file is temporary, you
must either open the file for reading or move it to a permanent
location in your app’s sandbox container directory before returning
from this delegate method.
The idea is just to copy from tmp directory to document directory and play from document directory.
Create a member variable:
var player = AVAudioPlayer()
Now implement your downloadSound method as below:
func downloadSound(url:URL){
let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let desURL = docUrl.appendingPathComponent("tmpsong.m4a")
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URLData, response, error) -> Void in
do{
let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)
if isFileFound == true{
print(desURL) //delete tmpsong.m4a & copy
try FileManager.default.removeItem(atPath: desURL.path)
try FileManager.default.copyItem(at: URLData!, to: desURL)
} else {
try FileManager.default.copyItem(at: URLData!, to: desURL)
}
let sPlayer = try AVAudioPlayer(contentsOf: desURL!)
self?.player = sPlayer
self?.player.prepareToPlay()
self?.player.play()
}catch let err {
print(err.localizedDescription)
}
})
downloadTask.resume()
}
This is just a sample solution.
I seem to be having issues while loading a PDF to my WebView in Swift.
Printing out all the files in the Documents directory results in:
file:///Users/adriandavidsmith/Library/Developer/CoreSimulator/Devices/B537EBE4-14AE-439A-B84B-31342E233367/data/Containers/Data/Application/E791BF20-CC53-4FBB-B34A-F73CED74EB5D/Documents/DOCUMENT.pdf
However, when I attempt to load that file into a WebView nothing gets shown. As if it is unable to find the file.
if let pdf = NSBundle.mainBundle().URLForResource("DOCUMENT", withExtension: "pdf", subdirectory: "Documents", localization: nil){
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
Any thoughts/ideas?
Swift 3 compatible
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent( "example.pdf") as URL
let data = try! Data(contentsOf: pdfURL)
let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
view.addSubview(webView)
The E791BF20-CC53-4FBB-B34A-F73CED74EB5D is application folder in which you have Documents folder containing the pdf file which you want to view.
This will give path of Documents folder.
let fileManager = NSFileManager.defaultManager()
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
print(documentsUrl)
You need to change code
let pdf = documentsUrl + "/<your pdf file name>"
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
Hope this works for you.
You are fetching it from bundle not from document directory.
Try this....
var pdf = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL
pdf = pdf?.URLByAppendingPathComponent( "ST_Business%20Times_07022016.pdf")
let req = NSURLRequest(URL: pdf)
webView.loadRequest(req)
Please check you path has valid file exist or not before loading the file.
let webView : UIWebView!
webView = UIWebView()
webView.frame = self.view.bounds
self.view.addSubview(webView)
let PDF_FILE_PATH = NSBundle.mainBundle().pathForResource("ST_Business%20Times_07022016", ofType: "pdf")
let checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(PDF_FILE_PATH!))
{
print("FILE AVAILABLE");
let req = NSURLRequest(URL: NSURL(string: PDF_FILE_PATH!)!)
webView.loadRequest(req)
}
else
{
print("FILE NOT AVAILABLE");
}