繁体   English   中英

如何在不使用第三方库的情况下在 swift2 中下载页面?

[英]How to download a page in swift2 without using third party libraries?

我正在尝试在应用程序中显示下载的 HTML 页面。 请解释不使用任何第三方库的最简单方法。

干杯,

无需下载即可在应用中显示 html 页面

 let pageUrl = NSURL (string: "http://www.stackoverflow.com");
 let req = NSURLRequest(URL: url!);

如果你想显示一个本地文件,你可以这样显示

let htmlfilePath = NSBundle.mainBundle().URLForResource("filename", withExtension: "html");
    let req = NSURLRequest(URL: htmlfilePath !);
    webview.loadRequest(req);

下载一个文件,你可以使用普通的 NSURLSession

您应该使用 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.
    }
}

你可以直接下载一个网站到一个 NSData 对象中,就像这个例子(Objective-C)一样;

    NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.raywenderlich.com/tutorials"];
    NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];

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 在这里有一个很棒的教程;

https://www.raywenderlich.com/14172/how-to-parse-html-on-ios

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM