IOS/Swift: Open PDF from a local path into a Web View - ios

I previously used below code to open up a dummy PDF, just for testing purpose, and now for the actual project i have to load a pdf based on the table cell clicked that will give the exact path of the pdf at some local path.
self.termsPath = NSBundle.mainBundle().pathForResource("DemoForm", ofType: "pdf")!
let url = NSURL(fileURLWithPath: termsPath!)
let pdfRequest = NSURLRequest(URL: url!)
pdfWebView.loadRequest(pdfRequest)
pdfWebView.scalesPageToFit = true
Now i have thisvariable docPath that will be passed from the prepareforSegue when table cell is clicked, i tried to use this variable in place of DemoForm but it gives below error
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0
Where i'm i going wrong here? Can anyone help me.Thanks
EDIT: By the way my docPath refers to something like ".../.../.../.../Referral.pdf"

Related

Swift4 app crashes when loading local HTML [duplicate]

This question already has answers here:
WKWebView does load resources from local document folder
(8 answers)
Closed 5 years ago.
While working on a web app for weeks, I used a external URL in my (WKWebView) web view. Now I'm moving towards production I want to embed the webapp and load a local webpage.
I simply moved from
let url = URL(string: "http://hidden-url.com/")
self.webView!.load(URLRequest(url: url!))
To
let url = URL(string: Bundle.main.path(forResource: "index_prod", ofType: "html")!)
self.webView!.load(URLRequest(url: url!))
But this causes my app to crash. I'm sure the file is loaded correctly and a print before, in-between and after the lines will appear in the console.
The error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
You need to load the string content from the file, use contentsOfFile method to get the string and use loadHTMLString method of webview, print the error or create some enum which shows the error
enum WebError: Swift.Error {
case fileNotFound(name: String)
case parsing(contentsOfFile: String)
}
guard let url = Bundle.main.path(forResource: "index_prod", ofType: "html") else {
throw WebError.fileNotFound(name: file) // throw file not found error
}
do {
let html = try String(contentsOfFile: url)
self.webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
} catch {
throw WebError.parsingError(contentsOfFile: file)
}

AVPlayer - Play from Local URL

Surprisingly i have not been able to find an answer to this despite many searching.
I have a file that has been cached, i can retrieve the cache directory and file name which i believe to be the url?
this is code to get the file and then play it
let cachedFilePath = getCachedFilePath.result as! String
audioFileURL = cachedFilePath
self.audioPlayerItem = AVPlayerItem(url: NSURL(string: audioFileURL!) as! URL)
This is what is returned if i print audioFileURL:
/Users/Genie/Library/Developer/CoreSimulator/Devices/A2FB00CE-B018-4FDF-9635-35FD6678DF8D/data/Containers/Data/Application/E18B5E89-B973-4277-AA5C-1378C69D80CD/Library/Caches/Parse/PFFileCache/7e4a8fc0eb37b655b859e4959f986da2_The%20Name%20of%20the%20Wind%2017-92.mp3
The player loads but it never plays, It just sits there spinning. so i am wondering if i am passing the url to the player correctly?
i read on one thread to use file:// before it but that didn't work.
In the place where you're creating an NSURL, you have the replace the argument name string to fileURLWithPath
Change
NSURL(string: audioFileURL!)
to
NSURL(fileURLWithPath: audioFileURL!)
Also, why are you casting NSURL to URL ? Why not use URL directly?
try like this,i hope it will work for you.
self.audioPlayerItem = AVPlayerItem(url:NSURL(fileURLWithPath: audioFileURL!) as! URL)
AVPlayerItem(url:URL(fileURLWithPath: Bundle.main.path(forResource: "filename", ofType: "mp4")!))
And make sure your video is added to the bundle:
project root > your Target > Build Phases > Copy Bundle Resources.

View Downloaded PDF on UIWebView

I have managed to download pdf file to the device.
I get this file:///var/mobile/Containers/Data/Application/DBC9AFAB-3FD4-4D06-82F5-0577251001A7/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf path
So I tried to open it on an UIWebView like this
let downloadedFilePath = "file:///var/mobile/Containers/Data/Application/DBC9AFAB-3FD4-4D06-82F5-0577251001A7/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf"
let filePathURL = NSURL(fileURLWithPath: downloadedFilePath);
webView.loadRequest(NSURLRequest(URL: url));
But the WebView fails to load the pdf. It only shows a blank webview
Any ideas why this does not work?
You code looks ok but the path is not
let downloadedFilePath = "///var/mobile/Containers/Data/Application/DBC9AFAB-3FD4-4D06-82F5-0577251001A7/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf"
let filePathURL = NSURL(fileURLWithPath: downloadedFilePath);
webView.loadRequest(NSURLRequest(URL: url));
Try this hope it works.
For checking that the file exist Open a new finder and press Command+Shift+G after that copy and paste the file path and press enter
If the file load then the file exist. File path in your case is " ///var/mobile/Containers/Data/Application/DBC9AFAB-3FD4-4D06-82F5-0577251001A7/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf "

exc-bad-instruction code=i386_invop

I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}

Swift - pathForResource inDirectory parameter

I'm making a very simple app that uses a UIWebView to display a pdf map that can be zoomed in on, panned, etc.
However, when creating a target url for the pdf, the pathForResource call isn't working right. This is my code:
var targetURL : NSURL = NSBundle.mainBundle().pathForResource(filename, ofType: type)
I get an error on the parentheses before "filename", that says Missing argument for parameter 'inDirectory' in call. I tried adding an argument for this:
var targetURL : NSURL = NSBundle.mainBundle().pathForResource(filename, ofType: type, inDirectory: "Map")
I don't know what to put for inDirectory, because I don't know what the directory is - I added the file to my project and it is in the same folder as my ViewController.swift file. Anyway, it doens't really matter, because I get the following error in the same place, Extra argument 'inDirectory in call.
What do I do?
pathForResource() does not return a NSURL object, but a String?. Declare your variable accordingly and it should work.
var targetURL : String? = NSBundle.mainBundle().pathForResource(filename, ofType: type)
Or, of course, if you would rather - just use URLForResource() instead.
var targetURL : NSURL? = NSBundle.mainBundle().URLForResource(filename, withExtension: type)
I was having this same problem. In my case it was because my variable (in your case type) needed to be unwrapped. Adding a bang ! made the error go away and made the code execute.

Resources