ios 如何使用 Swift 从 URL 获取 HTML 源代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26134884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:56:39  来源:igfitidea点击:

How To Get HTML source from URL with Swift

iosswiftnsurl

提问by Alex Beals

I need to look at the HTML of a page given by a certain URL. If I have this, what is the most efficient and synchronous way to get the HTML source for that URL using Swift? I haven't been able to find a concise way online that returns it into a variable as opposed to printing it in a completionHandler.

我需要查看某个 URL 给出的页面的 HTML。如果我有这个,使用 Swift 获取该 URL 的 HTML 源的最有效和同步的方法是什么?我一直无法在网上找到一种简洁的方法将它返回到一个变量中,而不是在 completionHandler 中打印它。

I need to manipulate the source outside of whatever call uses the URL. How is this done in Swift?

我需要在使用 URL 的任何调用之外操作源。这是如何在 Swift 中完成的?

回答by DCMaxxx

Disclaimer : Since this is getting quite a lot of views, I just want to remind everyone that this answer here is synchronous, and will block your app if you do it on the main thread. You should always do this asynchronously (in a background thread), but the question asked for a synchronous method, so it would be out of scope to explain how to do it here.

免责声明:由于这获得了相当多的观点,我只是想提醒大家,这里的答案是同步的,如果您在主线程上进行,则会阻止您的应用程序。您应该始终异步执行此操作(在后台线程中),但该问题要求使用同步方法,因此在此处解释如何执行此操作超出了范围。



You should probably look at the method :

你应该看看这个方法:

+ stringWithContentsOfURL:encoding:error(docs)

+ stringWithContentsOfURL:encoding:error文档

You would call it like this in Objective C :

你会在 Objective C 中这样称呼它:

NSString *myURLString = @"http://google.com";
NSURL *myURL = [NSURL URLWithString:myURLString];

NSError *error = nil;
NSString *myHTMLString = [NSString stringWithContentsOfURL:myURL encoding: NSUTF8StringEncoding error:&error];

if (error != nil)
{
    NSLog(@"Error : %@", error);
}
else
{
    NSLog(@"HTML : %@", myHTMLString);
}

So in Swift 3 and 4, the equivalent would be :

所以在 Swift 3 和 4 中,相当于:

let myURLString = "https://google.com"
guard let myURL = URL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
    print("HTML : \(myHTMLString)")
} catch let error {
    print("Error: \(error)")
}

You might want to adapt the encoding (see the constants) depending on which encoding your page's using.

您可能希望根据页面使用的编码来调整编码(请参阅常量)。



Old answer, Swift 2.2 :

旧答案,Swift 2.2:

let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOfURL: myURL)
    print("HTML : \(myHTMLString)")
} catch let error as NSError {
    print("Error: \(error)")
}


Old answer, Swift 1.2 :

旧答案,Swift 1.2:

let myURLString = "http://google.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)

    if let error = error {
        println("Error : \(error)")
    } else {
        println("HTML : \(myHTMLString)")
    }
} else {
    println("Error: \(myURLString) doesn't seem to be a valid URL")
}

回答by Crashalot

Swift 3:

斯威夫特 3:

    if let url = URL(string: "https://www.google.com/trends/hottrends/atom/hourly") {
        do {
            let contents = try String(contentsOf: url)
            print(contents)
        } catch {
            // contents could not be loaded
        }
    } else {
        // the URL was bad!
    }

回答by Meseery

An updated @DCMaxx answer to Swift 2.2 :

对 Swift 2.2 的更新@DCMaxx 回答:

let myURLString = "http://www.yahoo.com"

if let myURL = NSURL(string: myURLString) {
    var error: NSError?
    let myHTMLString = try! NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)

    if let error = error {
        print("Error : \(error)")
    } else {
        print("HTML : \(myHTMLString)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}

回答by ha100

more compact functional example

更紧凑的功能示例

let myURLString = "https://google.com"

let myHTMLString = try URL(string: myURLString)
    .flatMap { try Data(contentsOf: 
let myURLString = "https://duckduckgo.com/"

if let myURL = NSURL(string: myURLString) {

    do {
        let myHTMLString = try String(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)
        print("HTML : \(myHTMLString)")
    } catch {
        print("Error : \(error)")
    }
} else {
    print("Error: \(myURLString) doesn't  URL")
}
) } .flatMap { String(data: ##代码##, encoding: .ascii) }

回答by Javier Cadiz

This is the way to go in Swift 2:

这是 Swift 2 的方法:

##代码##

Also as an extrarelated to previous answers:
Note that Swift 2 introduces a new error handling approach that produces much clearer code for programmers to read, it does away with complexities like &to pass in NSErrors, and it gives you greater safety by ensuring you catch all errors.

另外作为与先前答案相关的额外内容
请注意,Swift 2 引入了一种新的错误处理方法,该方法可为程序员生成更清晰的代码以供阅读,它消除了&传入之类的复杂性NSErrors,并通过确保捕获所有内容为您提供更大的安全性错误。

Only use try!if you are 100% sure that the call won't fail.

try!当您 100% 确定呼叫不会失败时才使用。

Further reading:https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch

进一步阅读:https : //www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch