你应该看看方法:
stringWithContentsOfURL:encoding:error(docs)
你可以在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);
}
所以在Swift 3中,相当于:
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)")
}
您可能需要根据页面使用的编码来调整编码(请参阅constants).
老回答,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)")
}
老回答,斯威夫特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")
}