reference to local file is invalid - swift

This view is to display a local html file. When I launch it, the view never displays, the screen just hangs on the calling view. The exception is a nil value for let fileURL =.
import UIKit
import WebKit
class ViewController2: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let fileURL = URL(fileURLWithPath: Bundle.main.path(forResource:"about", ofType: "html")!)
webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
}
}

You don´t need to cast the Bundle.main.path(forResource:"about", ofType: "html") to URL. Do it like this instead:
let fileURL = Bundle.main.url(forResource: "about", withExtension: "html")!
webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
Update:
Remember to also add the file in your Project settings > Your project target > Build Phases > Copy bundle resources otherwise it won´t work. When you add the file to your project remeber to:
Check "copy items if needed"
Select "create folder references"

Related

Swift 5.3 macOS - Load Local HTML

I am trying to load a local html based website into my macOS app and I am hitting issues, I have this working in iOS but not macOS.
My ViewController.swift looks like this
import Cocoa
import WebKit
class ViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfig = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfig);
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let htmlURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
webView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL.deletingLastPathComponent())
}
}
The App runs but then I get this output in the console in Xcode:
WebPageProxy::tryReloadAfterProcessTermination: process crashed and the client did not handle it, not reloading the page because we reached the maximum number of attempts
The documentation for what I am trying to do seems to be lacking I wonder if anyone can help me sort this out please.
After some more digging I needed to do 2 things:
Amend my viewDidLoad() code:
let htmlURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "polarix-website")!
webView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL.deletingLastPathComponent())
view = webView
Enable Outgoing Connections (Client) in the Signing & Capabilities

How to load Microsoft file like docx in swift via UIWebView

I have been working on ios app which now i am facing some problems. I want to load some files like docx, xls using UIWebView. It gets me white screen on my actual device.
#IBOutlet weak var fileServerWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let path = Bundle.main.path(forResource: "easychair", ofType: "docx"){
let targetUrl: URL = URL(fileURLWithPath: path)
let request = URLRequest(url: targetUrl as URL)
fileServerWebView.delegate = self
fileServerWebView.scalesPageToFit = true
fileServerWebView.loadRequest(request)
}else{
print("cannot get path")
}
// Do any additional setup after loading the view.
}
That is code that i tried to load that file from local. Thank you for your help.

Swift xcode macos PDFDocument(url: URL) does not create document

I am trying to learn how to display a .pdf file in Swift in an xcode project. I have code that works if the target file is in the project's bundle, but I cannot display a .pdf that is elsewhere in my user space. In the code that follows (lower half), "pdfURL2" prints out and is the correct URL. The code prints out "File Exists", so I know that the target file is accessible. It is a valid .pdf file that I can open with Preview. Using the xcode debugger, "test" is "nil". Following that, "pdfView.document = test" opens a view, but it is, of course, empty. If I surround the "test = PDFDocument(url: pdfURL2)" declaration with a guard" statement, the thread crashes. Hence, I have left that out.
How do I display a .pdf file that is not explicitly in xcode"s project bundle?
CODE FOLLOWS:
import Cocoa
import Quartz
class PDFViewController: NSViewController {
#IBOutlet weak var pdfView: PDFView!
override func viewDidLoad() {
super.viewDidLoad()
let fm = FileManager.default
// THIS Code does WORK (for test.pdf in bundle)
guard let pdfURL = Bundle.main.url(forResource: "test", withExtension: "pdf")
else { fatalError("PDF not found") }
guard let pdfDocument = PDFDocument(url: pdfURL)
else { fatalError("PDF document not created") }
pdfView.document = pdfDocument
// END of code that does WORK (for test.pdf in bundle)
// THis Code does NOT WORK for buildFile.pdf NOT in bundle
let pdfPath2 = "/Users/myaccount/Desktop/Problematic/buildFile.pdf"
let pdfURL2 = URL(fileURLWithPath: pdfPath2)
print("pdfURL2 = \(pdfURL2)")
if fm.fileExists(atPath: pdfPath2){
print("File Exists")
var test = PDFDocument(url: pdfURL2)
pdfView.document = test
}
// Do any additional setup after loading the view.
} // End ViewDidLoad
} // End PDFViewController

Play video from local file with tvOS

I want to play a little video (20 seconds) when my app opens on the Apple TV. But I can't find how to implement the URL from a local file.
This is what I've got so far, but unfortunately it doesn't work:
override func viewDidLoad() {
super.viewDidLoad()
// I know this is how to play a file from a webserver:
// player = AVPlayer(URL: NSURL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)
// But I can't find how to set the URL to a local file in the app
let path = NSBundle.mainBundle().pathForResource("bunny", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
player = AVPlayer(URL: url)
player?.play()
}
Your code seems fine. Maybe, you should try this:
In the Project Navigator select your Project Root > Your Target >
Build Phases > Copy Bundle Resources. Check to see that your video is
there, if not click the plus sign to add it.
Source: http://www.brianjcoleman.com/tutorial-play-video-swift/
I'd like to list the most compact way along with all four hurdles:
Import AVKit, Call the playVideo() function from viewDidAppear, watch
out for the correct Bundle access and make sure the file has the
correct target membership as stated by Ennio!
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video", ofType:"mov") else {
debugPrint("video.mov not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
}

Injecting a new stylesheet into a website via uiwebview using iOS8 Swift XCode 6

I've seen a few options on here using just Objective-C, but I'm having trouble doing this with Swift iOS8 in XCode 6. I'm using the uiwebview to load a website. For sake of example, let's say its google.com.
#IBOutlet var website: UIWebView!
var url = "http://www.google.com"
func loadUrl() {
let requestURL = NSURL(string: url)
let request = NSURLRequest(URL: requestURL!)
website.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
website.delegate = self
loadUrl()
}
func webViewDidFinishLoad(website: UIWebView) {
var jsscript = "some script here"
website.stringByEvaluatingJavaScriptFromString(jsscript)
}
Using Swift, how would I inject a whole new stylesheet into the website so I can overwrite many of the styles?
Also, I'd like the new stylesheet to exist in one of my app's directories. Where is the best directory for that to be? Under "Supporting files?" And, how would I call that path in my code?
It would also be nice if the website wouldn't load until the styles had been applied.
So, I think I found at least one way to accomplish appending styles to the webpage being loaded using Swift:
var loadStyles = "var script =
document.createElement('link');
script.type = 'text/css';
script.rel = 'stylesheet';
script.href = 'http://fake-url/styles.css';
document.getElementsByTagName('body')[0].appendChild(script);"
website.stringByEvaluatingJavaScriptFromString(loadStyles)
Using the now preferred WKWebView you can put the external css file, say tweaks.css in the root of your project or in a sub-folder, then you can inject it into your page like this:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let path = Bundle.main.path(forResource: "tweaks", ofType: "css") else { return }
let css = try! String(contentsOfFile: path).replacingOccurrences(of: "\\n", with: "", options: .regularExpression)
let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"
webView.evaluateJavaScript(js)
}
To make the file available:
Click your project
Click your target
Select Build Phases
Expand Copy Bundle Resources
Click '+' and select your file.
Also make sure that your controller implements WKNavigationDelegate:
class ViewController: UIViewController, WKNavigationDelegate