I want to show a local image from CachesDirectory in a webview.
The webview can't load it. The bundle doesn't contain the image!
I download the image from the server but I have a local HTML file with the image tag. How can I do it?
My path where the image exists:
/Users/adambella/Library/Developer/CoreSimulator/Devices/BFA8C179-EBC5-49A7-95F3-1ABA202F44AD/data/Containers/Data/Application/746BE86B-33D7-4A6F-8C4C-0E4453FE374C/Library/Caches/swift.imageloader.diskcached/
Anybody could give me a short example?
I downloaded it with ImageLoader.
Path with Name:
var path: String {
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
let directoryName = "swift.imageloader.diskcached"
return cacheDirectory + "/" + directoryName
}
let filePath = NSBundle.mainBundle().pathForResource("example", ofType: "html",inDirectory: "Directory")
let urlToFile = NSURL(fileURLWithPath: filePath!)
let request = NSURLRequest(URL: urlToFile, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 10.0)
and in webViewDidFinishLoad method:
webview2.stringByEvaluatingJavaScriptFromString("testImage('\(path)')")
function in html file:
function testImage(url) {
var mapDiv = document.getElementById("map");
mapDiv.innerHTML = "<img src=file://" + url + "/>";
}
This is Swift 4.2 code.
base URL in you can set Image URL
web.loadRequest(URLRequest.init(url: baseURL!))
If you have any query please comment
Related
I need url filepath be a URL (NSURL in old versions of Swift). I have this:
let paths = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true)
// NSString *documentsDirectory = [paths objectAtIndex:0];
let documentsDirectory = paths[0] as String
var filePath:String? = nil
var fileNamePostfix = 0
repeat {
filePath =
"\(documentsDirectory)/\(dateTimePrefix)-\(fileNamePostfix).mp4"
fileNamePostfix += 1
} while (FileManager.default.fileExists(atPath: filePath))
I need to convert this to URL for use in self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>) method.
I tried filePath as? URL() but it isn't correct.
you need to do:
let fileUrl = URL(string: filePath)
or
let fileUrl = URL(fileURLWithPath: filePath)
depending on your needs. See URL docs
Before Swift 3, URL was called NSURL.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
in swift 4 to convert to url use URL
let fileUrl = URL.init(fileURLWithPath: filePath)
or
let fileUrl = URL(fileURLWithPath: filePath)
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
To Convert file path in String to NSURL, observe the following code
var filePathUrl = NSURL.fileURLWithPath(path)
// here frit i want to save a mp4 file before saving i want to check is it alreday there.if there than create another name
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let savePathUrl = NSURL(string: ("\(documentsURL.appendingPathComponent("temp"))" + ".mp4"))
if FileManager.default.fileExists(atPath: **savePathUrl**)// here i get error
}
{
do
{
try FileManager.default.removeItem(atPath: **savePathUrl**)// here i get error
}
catch { }
}
First off, the way you create savePathUrl makes little sense. Replace:
let savePathUrl = NSURL(string: ("\(documentsURL.appendingPathComponent("temp"))" + ".mp4"))
with:
let savePathUrl = documentsURL.appendingPathComponent("temp.mp4")
And then for the two FileManager manager methods you need a file path. To get a file path from a file URL, you need to use the path property.
if FileManager.default.fileExists(atPath: savePathUrl.path) {
Webkit loading from .documentsURL html webpages, iOS device is not showing image, js, css files, works fine on simulators. What could be my bug in the code I have written?
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let urltostr = documentsURL.absoluteString
//print(urltostr)
let htmlurl = urltostr+"0/index.html"
let finalURL = URL(string: htmlurl)
let base = urltostr+"0/"
let baseUrl = URL(string: base)
//let baseUrl = URL(fileURLWithPath: base, isDirectory: true)
do {
let fileName = try String(contentsOf: finalURL!)
webview.loadHTMLString(fileName as String, baseURL: baseUrl)
} catch {
// catch error
print("Error web view get html")
}
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")
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");
}