你錯過了在這裏的參數:
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url usedEncoding:NSUTF8StringEncoding];
它應該是:
NSError *error = nil;
NSStringEncoding enc;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&enc error:&error];
由於它的既定NSString Reference:
- (instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding)enc error:(NSError **)error
請務必信任Xcode中的警告。在這種情況下,我認爲,它應該告訴您,在編譯代碼之前,它無法在NSString
類中找到方法簽名。
如果您不確定方法名稱或簽名,請務必檢查Apple的文檔。它會幫助你更快地編碼:D
編輯:我修復了@David建議的代碼,謝謝!
編輯:添加完整的代碼有一些更多的解釋
如果我理解正確的話,你只想NSData
轉換爲NSString
,你已經知道它是在UTF8編碼。
如果是這種情況,您使用了錯誤的方法。 您使用的方法是將NSData
轉換爲NSString
,並確定它是什麼編碼。這就是爲什麼您必須爲它提供NSStringEncoding指針。
返回到你的情況,這是你完整的代碼是什麼樣子:
NSError *error = nil; // I added this
NSURL *url = [[NSURL alloc] initWithString:@"http://google.com"];
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding // and changed this
error:&error]; // and added this
if ([my_string length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
message:@"A connection to the Internet is required to access this page."
delegate:self cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
但是,如果我錯了,這可能是您的完整代碼:
NSError *error = nil; // I added this
NSStringEncoding enc; // also this
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&enc // changed this
error:&error]; // and added this
if ([my_string length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
message:@"A connection to the Internet is required to access this page."
delegate:self cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
你只是想查看您的應用是否具有互聯網連接? –