How To Get HTML source from URL with Swift

前端 未结 5 1100
盖世英雄少女心
盖世英雄少女心 2020-12-04 22:41

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?

5条回答
  •  一向
    一向 (楼主)
    2020-12-04 23:01

    This is the way to go in Swift 2:

    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")
    }
    

    Also as an extra related 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.

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

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

提交回复
热议问题