[英]How to download a page in swift2 without using third party libraries?
I am trying to show the downloaded HTML page in the app.我正在尝试在应用程序中显示下载的 HTML 页面。 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无需下载即可在应用中显示 html 页面
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下载一个文件,你可以使用普通的 NSURLSession
You should use NSURLSession dataTaskWithURL to download your website data asynchronously:您应该使用 NSURLSession dataTaskWithURL 异步下载您的网站数据:
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);你可以直接下载一个网站到一个 NSData 对象中,就像这个例子(Objective-C)一样;
NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.raywenderlich.com/tutorials"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
Swift example; Swift 示例;
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; Ray 在这里有一个很棒的教程;
https://www.raywenderlich.com/14172/how-to-parse-html-on-ioshttps://www.raywenderlich.com/14172/how-to-parse-html-on-ios
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.