我正在尝试使用stringWithContentsOfURL:
从Web获取HTML文件。我的问题是,有时它有用,但有时却没有。例如,我尝试过:
NSString *string = [NSString stringWithContentsOfURL:
[NSURL URLWithString:@"http://www.google.com/"]
encoding:encoding1
error:nil];
NSLog(@"html = %@",string);
这可以正常工作,但是当我用
@"http://www.youtube.com/"
替换URL时,我只会得到“NULL”。有谁知道发生了什么事吗?是因为YouTube受到某种保护吗?
最佳答案
Google的主页使用ISO-8859-1编码(又名“Latin-1”或NSISOLatin1StringEncoding
)。 YouTube使用UTF-8(NSUTF8StringEncoding
),并且您使用encoding1
变量指定的编码必须与相关网页匹配。
如果您只想要该网页,而不真的在乎它的编码,请尝试以下操作:
NSStringEncoding encoding;
NSError *error;
NSString *string = [NSString stringWithContentsOfURL:
[NSURL URLWithString:@"http://www.google.com/"]
usedEncoding:&encoding
error:&error];
NSLog(@"html = %@",string);
该方法将告诉您编码是什么(通过将其写入
encoding
变量),但是您可以将其扔掉,然后专注于字符串。
关于objective-c - 无法使用stringWithContentsOfURL检索某些页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6166076/