URLWithString“http://google.com”VS URLWithString“http://apple.com”

时间:2012-05-29 10:05:33

标签: objective-c nsstring nsurl

我有以下代码。

NSURL *serverUrl = [NSURL URLWithString:@"http://google.com"];
NSError *error = nil;
NSString *stringFromStream = [NSString stringWithContentsOfURL:serverUrl encoding:NSUTF8StringEncoding error:&error];
NSLog(@"string is %@ error is %@", stringFromStream, error);

这段代码会产生以下错误

2012-05-29 11:57:46.914 [2221:f803] string is (null) error is Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x6a36c60 {NSURL=http://google.com, NSStringEncoding=4}

但如果我将网址更改为

NSURL *serverUrl = [NSURL URLWithString:@"http://apple.com"];

我会完美地工作。

1 个答案:

答案 0 :(得分:0)

内容的编码可能不是UTF-8。请尝试使用此方法:

- (id)initWithContentsOfURL:(NSURL *)url
               usedEncoding:(NSStringEncoding *)enc
                      error:(NSError **)error;

(完成后,您必须release NSString

Reference