How to insert user entered data into a local html document - ios

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.
}
}

Related

WKWebView: insert UIImage into web page

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:

Custom Address Search iOS mapkit

Learning swift 2/ Xcode 7 and creating a app iOS 9 where I can enter a custom address. I have mapkit working and can search regular address. I have my current location working. Instead of entering an address: "Number,Street, city, zip code", I want the user to enter: PR33.1 for example, and that would show the user that location. I have the long and lats for the custom address's, I've read many things on geocoding and annotations but nothing that would let me accomplish what I need. Can this be done? jSon file maybe.. I'm really new at this...
thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
let arbitraryString: [String:String] =
["161 RL2": "23908709138882,-106.7433588579297",
"40.9 RL112":"32.393144,-106.727762"]
#IBAction func enterButtonTapped(sender: AnyObject) {
if let textField = arbitraryString["161 RL2"] {
print(" \(textField).")
} else {
print("That is not in the dictionary.")
}
}
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.
}
}

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

Attempting to load Webview with PDF, receiving link from Parse

I am attempting to load a lunch menu PDF into a web view for a high school app that I am updating. Currently, it can load a PDF into the web view and display it just fine, but I want to speed up the monthly update process by having my app receive the link through Parse (Which I can update much quicker than updating the link in the app itself with Apple's 7 day review period), and then load the PDF. Currently, with what I have put together, my app will not load the PDF. Here's the entire view:
import UIKit
class AlaCarte_ViewController: UIViewController {
#IBOutlet weak var webviewAlaCarte: UIWebView!
var urlpath = String()
func loadAddressUrl(){
let requestURL = NSURL (string:urlpath)
let request = NSURLRequest(URL: requestURL!)
webviewAlaCarte.loadRequest(request)
alaCarteUpdate()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
clearPDFBackground(self.webviewAlaCarte)
}
func clearPDFBackground(webView: UIWebView) {
var view :UIView?
view = webView as UIView
while view != nil {
if NSStringFromClass(view?.dynamicType) == "UIWebPDFView" {
view?.backgroundColor = UIColor.clearColor()
}
view = view?.subviews.first as! UIView?
}
}
func alaCarteUpdate() {
var query = PFQuery(className: "AlaCarte")
query.getObjectInBackgroundWithId("rT7MpEFySU") {(AlaCarte: PFObject!, error: NSError!)-> Void in
if error == nil && AlaCarte != nil {
println(AlaCarte)
} else {
println(error)
}
let AlaCarteLink = AlaCarte["webaddress"] as! String
self.urlpath = AlaCarteLink
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadAddressUrl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
The link is stored in my Parse app as "webaddress" and does not contain end quotations. Adding them does not help. Any ideas?
It looks to me like you're not telling the web view to load the URL once it's retrieved from Parse.
Try adding the following lines after self.urlpath = AlaCarteLink in alaCarteUpdate().
let requestURL = NSURL (string:self.urlpath)
let request = NSURLRequest(URL: requestURL!)
self.webviewAlaCarte.loadRequest(request)
I think it would also be a good idea to add a function that specifically loads a url string into your web view, so you can call it from both inside alaCarteUpdate(), and loadAddressUrl(), and avoid the duplicate 3x lines. I've assumed that you're loading the URL in loadAddressURL() so that you can show a local/cached document while retrieving the latest from Parse.

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