WKWebView: insert UIImage into web page - ios

In iOS, given a web page loaded inside a WKWebView, how can I show my own UIImage inside the HTML?
Thanks

One way to do it is using Base64 encoding. The following should be a completely working example, assuming you wire up a UIWebView and have an image of the correct name:
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let image = UIImage(named: "Castle"),
let data = UIImagePNGRepresentation(image) {
let base64 = data.base64EncodedString(options: [])
let url = "data:application/png;base64," + base64
let html = "<html><head></head><body><h1>Hello World!</h1><img src='\(url)'></body></html>"
webView.loadHTMLString(html, baseURL: URL(fileURLWithPath: ""))
}
}
}
I tried to do this in Playground, but couldn't get the webView to display, so it's a minimal app...
Output:

Related

How to insert user entered data into a local html document

I'm very new to Swift and I'm struggling a bit with a simple task. I have made a simple app which will launch a local HTML file.
I now want to add a text box that appears, asking the user "Enter IP address". Then, that text will be inserted into the HTML file in 3 different places.
Does anyone have any ideas on this? Or know of a good site which might have some tutorials which relate to this idea? Here's my code so far:
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet weak var htmlload: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let htmlpath = Bundle.main.path(forResource: "index", ofType: "html")
let url = URL(fileURLWithPath: htmlpath!)
let request = URLRequest(url: url)
htmlload.load(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

WKWebView is not getting intialized in swift 4 xcode 10

Could anyone help me in understanding why my webView is not getting initialized here. I am getting the following error because webView is nil.
Fatal error: Unexpectedly found nil while unwrapping an Optional value
What exactly I am missing here?
import UIKit
import WebKit
class MemoriesViewController: UIViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear( animated )
let urlString:String = "https://www.apple.com"
let url:URL = URL(string: urlString)!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
}
}
Screenshot for better clarity where the error is actually happening:
Add Webkit.Frameworks to Linked Framework and Libraries
You can then add the Outlet for WKWebView and use your code
import UIKit
import WebKit
class MyWebViewController: UIViewController {
#IBOutlet weak var myWV: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let urlString:String = "https://www.apple.com"
let url:URL = URL(string: urlString)!
let urlRequest:URLRequest = URLRequest(url: url)
myWV.load(urlRequest)
}
}
In Xcode 10, you can foll bellow the step:
Click the project
Go to build phase
Go to Link Binary with Libraries
Click add plus sing under Link Binary with Libraries
open a windows & search Webkit.framework
add & enjoy it
Show bellow image
The problem was my output was not connected to the storyboard. That's why #IBOutlet was not getting initialized.

Integrate web text into App (Swift)

I am having a news section in the App and i want to renew it through a website that shows the text and pictures it should copy how do i do that?
I just want that it exactly copies the text and pictures from a website.
Thanks in advance.
You can use UIWebView for that! First, drop a web view on the scene and then:
Here is the code for SWIFT 2:
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad(){
super.viewDidLoad()
let url = NSURL(string: "http://www.google.com") // instead of "http://www.google.com", you put the website link you want, but with "http://" or "https://"
let urlRequest = NSURLRequest(URL: url!)
webView.loadRequest(urlRequest)
}
}
Version For SWIFT 3:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate{
#IBOutlet var webView: UIWebView!
override func viewDidLoad(){
super.viewDidLoad()
let url = URL(string: "http://www.booking.com") // instead of "http://www.google.com", you put the website link you want, but with "http://" or "https://"
let urlRequest = URLRequest(url: url!)
webView.loadRequest(urlRequest)
}
}
So at the end you need to implement rss reader if your website supports.
https://www.raywenderlich.com/2636/rss-reader-tutorial-for-ios-how-to-make-a-simple-rss-reader-iphone-app
If website does not support then you could implement below ways.
Open that URL in UIWebView or Copy though each text and image on your server and make API to display on app.

How to only display part of web page content (swift)

I am brand new to coding (no background in any programming language at all). I am trying to learn swift. I am wanting to create a simple weather app that displays weather information in text once the user enters a city. I am grabbing the content from weather-forecast.com. I have figured out how to load the web content, but I want to only display a snippet (one paragraph) of the content from the page, not the whole page. Can someone please show me how to do that?
{
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var cityText: UITextField!
#IBOutlet weak var webContent: UIWebView!
#IBAction func GoButtonPressed(sender: AnyObject) {
let url = NSURL (string: "http://www.weather-forecast.com");
let requestObj = NSURLRequest(URL: url!);
webContent.loadRequest(requestObj);
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}
Here is an example of simple view controller which loads only part of the website dribble.com. The controller has method to select the DOM element and only show that element. It is quite simple, yet powerful enough to show how you could work further on this.
import UIKit
import JavaScriptCore
import WebKit
class TestViewController: UIViewController {
private weak var webView: WKWebView!
private var userContentController: WKUserContentController!
override func viewDidLoad() {
super.viewDidLoad()
createViews()
loadPage("https://dribbble.com/", partialContentQuerySelector: ".dribbbles.group")
}
private func createViews() {
userContentController = WKUserContentController()
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
let webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(webView)
let views: [String: AnyObject] = ["webView": webView, "topLayoutGuide": topLayoutGuide]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][webView]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[topLayoutGuide][webView]|", options: .allZeros, metrics: nil, views: views))
self.webView = webView
}
private func loadPage(urlString: String, partialContentQuerySelector selector: String) {
userContentController.removeAllUserScripts()
let userScript = WKUserScript(source: scriptWithDOMSelector(selector),
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true)
userContentController.addUserScript(userScript)
let url = NSURL(string: urlString)!
webView.loadRequest(NSURLRequest(URL: url))
}
private func scriptWithDOMSelector(selector: String) -> String {
let script =
"var selectedElement = document.querySelector('\(selector)');" +
"document.body.innerHTML = selectedElement.innerHTML;"
return script
}
}
The view controller shown in the example above only loads photos, design section inside the dribble website.
You won't be able to do that easily - UIWebView doesn't have any API to expose the structure of the web page it is loading nor to control/permit partial loading of a page.
Perhaps you might be able to scrape the content of the page and then display it, but you would do this before loading it in the UIWebView, and after you've scraped it then a web view is probably not the best way to display it anyway.
Do some searching for html and web scraping to see what the term means.
Alternatively if you know the web page content structure, you can inject javascript into the page as UIWebView is loading it and that javascript would stop the other parts of the page from being displayed (but if weather-forecast.com change the structure of their html in the future your javascript would probably no longer work)
Either way, both seems a bit too complex for a beginner though unless perhaps you can pick things up quick and are competent but its a lot to learn.
Instead of getting data off a website you could install a weather API into your app. This would be quicker and probably easier as with most weather API's you could choose what information to display.
Some more information on how to install a weather API is to go to this website.
Hope I solved your problem, Toby

DELAY issues: how to apply styles immediately or not show loaded webpage until styles are applied?

Technologies Used: XCode 6, iOS8, Swift
I'm loading a webpage in a uiwebview and I'm also appending a new stylesheet to the body of that webpage and overwriting some of its styles. But, there is a delay (maybe 1 second or 2) between when the webpage loads and the styles are applied so you can see the webpage before its restyled. I'm using javascript to append the new styles to the body of the webpage. How can I fix this so that the webpage will only show with the styles are already applied? Here is my code:
import UIKit
class SecondViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var website: UIWebView!
var url = "http://www.fake-website-url.net"
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 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)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Note, I'm using Swift.
What I would do is create a property to store the downloaded page. Then override the property setter to add your custom style sheet after the page is saved to that property. Then finally load it into your Web View.
Hope that makes sense.

Resources