I am having trouble loading a local HTML file. Here is my code. please help.
let URL = NSBundle.mainBundle().pathForResource("index2", ofType: "html")
let request = NSURLRequest(URL: url!)
Webview.loadRequest(request)
by use the following code. I have manage to load the html file but it doesn't load up the CSS!
let htmlFile = NSBundle.mainBundle().pathForResource("index1", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
GSFWebView.loadHTMLString(html!, baseURL: nil)
Simply write this code inside your ViewDidLoad i have added url of this page as example, just replace it with yours. On storyboard you don't need to do anything, if you have any extra view added on you view controller as container for website then replace self.view in my code with your view.
let myWebView:UIWebView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
//add your url on line below
myWebView.loadRequest(URLRequest(url: URL(string: "https://stackoverflow.com/questions/26647447/load-local-html-into-uiwebview-using-swift")!))
self.view.addSubview(myWebView)
And if you want to load page from local file, you can do it by defining url this way.
Swift 2
let url = NSBundle.mainBundle().URLForResource("webFileName", withExtension:"html")
Swift 3
let url = Bundle.main.url(forResource: "webFileName", withExtension: "html")
I only had to add this code to the viewDidLoad method:
1- First of all, you have to get the local URL from the Bundle. (previously, I added the index.html file to the project, copying when asked)
2- Then you have to create the request URL to be loaded from the webView.
3- After all, add the new webView created as a subView from the main view.
That worked for me.
if let url = Bundle.main.url(forResource: "index", withExtension: "html"){// 1st step
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url as URL) // 2nd step
webView.load(request)
self.view.addSubview(self.webView) // 3rd step
}
Related
Whenever I try to use .addAttachmentURL, it does not attach anything. The ViewController is presented with nothing within the body of the text. The URL is a path to the pdf data (I don't know if that makes a difference) in my file defaults. Is there any way I can send a PDF through text like this? I have not found anything by looking through documentation or StackOverflow. Also, I haven't implemented it yet, but I was wondering if there was a way to also attach PNGs to this message I am sending along with the PDF.
func getFileManager() -> NSString {
let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString)
return filePath
}
func displayMessageInterface() {
let composeVC = MFMessageComposeViewController()
composeVC.messageComposeDelegate = self
// Configure the fields of the interface.
composeVC.recipients = ["000000000"]
var url = URL(string: self.getFileManager() as String)!
url.appendPathComponent("my_report.pdf")
composeVC.addAttachmentURL(url, withAlternateFilename:
"this file")
// Present the view controller modally.
if MFMessageComposeViewController.canSendText() {
self.present(composeVC, animated: true, completion: nil)
} else {
print("Can't send messages.")
}
}
You are using the wrong URL initializer. URL(string:) initializer expects a scheme, in this case file://. You need to use URL(fileURLWithPath:) initializer or simply get the document directory URL using FileManager urls method:
extension URL {
static let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
let url = URL.documentDirectory.appendingPathComponent("my_report.pdf")
I am not sure what you mean when you say "The URL is a path to the pdf data in my file defaults". If you have included your file in your project Bundle you need to use its url(forResource:) method.
let url = Bundle.main.url(forResource: "my_report", withExtension: "pdf")!
I am attempting to load local images from my local Bundle into my WkWebView but have not been successful.
This is my index.html:
<div>
<img src='./images/test.png'>
<p>Test Para</p>
</div>
My folder structure:
- web
-- images
-- test.png
-- index.html
- ViewController
Code in ViewController that loads the HTML
Attempt 1:
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: true)
webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
Attempt 2:
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
Attempt 3:
let htmlPath = Bundle.main.path(forResource: "index", ofType: "HTML")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlString as String, baseURL: baseUrl)
} catch {
// catch error
}
The solutions attempted above were suggested from this post and this. All the above returns the following result:
The problem is that this statement is wrong:
My folder structure:
- web
-- images
-- test.png
-- index.html
That may be what the Project navigator looks like, but those yellow things in the Project navigator ("web", "images") are not folders. They are just organizational devices for the Project navigator itself (groups), to help you find your stuff. In the built app, your resources are being loaded flat into the app bundle, so that test.png and index.html are at the same level together, namely, the top level of the bundle.
If what you really wanted was in fact a "web" folder with that structure inside your app bundle, then you needed this to be a folder reference, which is a very different thing.
Downloading an mp3 and saving it into the Library/caches folder works, But accessing it later doesn't.
Checking if the song really exists, i opened up Finder and went to the simulator folders. and my folder looks like this:
My song is located at: Library/Caches/Digger/Flower.mp3
Trying to access this using AVPlayer:
let folderName = "Digger"
let fileName = "Flower.mp3"
let url = FileManager.default
.urls(for: .cachesDirectory, in: .userDomainMask)[0]
.appendingPathComponent(folderName).appendingPathComponent(fileName)
var urlString = url.absoluteString
print("MyPath: \(urlString)")
urlString.removeSubrange(urlString.range(of: "file://")!)
let player = AVPlayer(url: URL(string: urlString)!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
player.play()
}
But it doesn't work.
Simulator screenshot upon runtime:
Your URL handling is incorrect.
Replace these lines:
var urlString = url.absoluteString
print("MyPath: \(urlString)")
urlString.removeSubrange(urlString.range(of: "file://")!)
let player = AVPlayer(url: URL(string: urlString)!)
with:
let player = AVPlayer(url: url)
url already is the URL that you need. No need to try to convert it in any way.
For reference, use url.path to convert a file URL into a path string. And if you need to create a URL from a path string, use URL(fileURLWithPath:), not URL(string:). Only use URL(string:) with a string that has a URL scheme such as file://, https://, etc.
I'm trying to read the data from a txt file on macOS. I use String(contentsOf:) and Bundle.main.path(forResource:) like I would on iOS. However, this doesn't work on macOS. I have tried several solutions from other posts but because of macOS they don't seem to work.
Thanks in advance.
Edit:
My code:
let path = Bundle.main.path(forResource: "file", ofType: "txt")! // no error
let url = URL(string: path)! // no error
let contents: String
do {
contents = try String(contentsOf: url)
} catch {
print(error) // Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported."
contents = "ERROR"
}
print(contents)
I can save the data to a folder on disk, but I want to ship this file with my app.
URL(string is the wrong API. It's only for URL strings starting with a scheme (http://, file://)
For file system paths you have to use URL(fileURLWithPath.
But in this situation there is a much better way
Replace
let path = Bundle.main.path(forResource: "file", ofType: "txt")!
let url = URL(string: path)! // no error
with
let url = Bundle.main.url(forResource: "file", withExtension: "txt")
I have a url like this:
http://*****.ru/cgi-bin/****/****/cgi.exe?LNG=&C21COM=2&I21DBN=EKU_XML&P21DBN=EKU&Z21ID=1482179537193C7C43181117E030&Image_file_name=%5CFULL%5FTEXT%5CELBIB%5CNarodnye%5Fprazdniki%2Epdf&IMAGE_FILE_DOWNLOAD=1&SECUR=LOG&RIGHT=ALL
this url for downloading *.PDF file.
I use this function for download file
//method to be called to download
func download(url: URL)
{
self.url = url
//download identifier can be customized. I used the "ulr.absoluteString"
let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTask(with: url)
task.resume()
}
After calling this function, I get cgi.exe file, not pdf file. Why it's happen?
From your URL I can assume, that you are starting your cgi.exe with parameters to generate your pdf file. I think, that you need to send a request to your cgi.exe to generate file and place in response proper link to generated .pdf file. And then start your downloading operations with this URL.
Hope it helps