簡體   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