2014-06-05 50 views
0

有一個錯誤下面是代碼:我想從互聯網上獲取數據,但我在連接

[NSString alloc] initWithContentsOfURL:url usedEncoding:NSUTF8StringEncoding

Xcode中給出了錯誤:no visible @interface for "NSString" declares the selevtor "initWithContentsOfURL:url usedEncoding

那麼,什麼是錯在這裏?

這裏全碼:

NSURL *url = [[NSURL alloc] initWithString:@"http://google.com"]; 
NSStringEncoding encoding; 
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url usedEncoding:NSUTF8StringEncoding]; 

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]; 
} 

`

+0

你只是想查看您的應用是否具有互聯網連接? –

回答

0

你錯過了在這裏的參數:

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]; 
} 
+0

您仍然會收到錯誤。 'usedEncoding:'參數是通過引用傳遞的,所以你需要傳入NULL或NSStringEncoding指針。 –

+0

哦!謝謝你指出。實際上我從來沒有使用過這種方法之前大聲笑。 – 3329

+0

所以有人可以在這裏留下完整的代碼 – user3708025