objective-c - 无法使用stringWithContentsOfURL检索某些页面

标签 objective-c cocoa-touch ios nsurl

我正在尝试使用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/

相关文章:

iPhone SDK 4 "Half curl page transition"

ios - 通过点击通知检查应用程序是否已打开

ios - Swift 中 iOS 8 中的 startBrowsingForNearbyPlayersWithHandler()

html - 在 iOS 上播放 HTML5 视频时没有声音

ios - 如何创建分段时间线数据集(使用 Objective-C)

objective-c - 如何从 cocoa 中的 CFTypeRef 获取窗口号?

objective-c - Swift 优化不起作用?

objective-c - 动画加载 subview

objective-c - 将任意形状的 CGPath 动画化为矩形

ios - 为什么调用我的 CABasicAnimation 在 vi​​ewDidAppear 中不起作用?