I am trying to show the downloaded HTML page in the app. Please explain the simplest way to do so without using any third party libraries.
cheers,
You can show a html page in app without downloading
let pageUrl = NSURL (string: "http://www.stackoverflow.com");
let req = NSURLRequest(URL: url!);
if you want to show a local file you show like this
let htmlfilePath = NSBundle.mainBundle().URLForResource("filename", withExtension: "html");
let req = NSURLRequest(URL: htmlfilePath !);
webview.loadRequest(req);
to download a file you can use plain NSURLSession
You should use NSURLSession dataTaskWithURL to download your website data asynchronously:
import UIKit
class ViewController: UIViewController {
let stackoverflowLink = "https://stackoverflow.com/questions/36315798/how-to-download-a-page-in-swift2-without-using-third-party-libraries"
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: stackoverflowLink) else { return }
print("LOADING URL")
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
guard
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
let data = data where error == nil,
let htmlCode = String(data: data, encoding: NSUTF8StringEncoding) // make sure you use the correct String Encoding
else { return }
print( htmlCode)
print("URL LOADED")
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You can download a web site directly into an NSData object as in this example (Objective-C);
NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.raywenderlich.com/tutorials"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
Swift example;
let aString = "http://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-xfp1/t31.0-8/q88/s720x720/10848858_907722502601079_2834541930671169073_o.jpg"
let url = NSURL(string: aString)
let data = NSData(contentsOfURL: url!)
Ray has a great tutorial here;
https://www.raywenderlich.com/14172/how-to-parse-html-on-ios
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.