2011-05-07 23 views
1

在我的一個應用程序中,我想異步調用我寫的一個php頁面(http://serveradress/page.php?date = 20111231 ),並且我一定會知道該頁面是否可以被調用(沒有404錯誤,php服務器關閉,自定義404頁面,缺少互聯網連接或者類似的東西)。 我已經計劃讓php頁面在其主體或標題中返回一個非常簡單的HTML頁面,並且只有「OK」。iPhone - 異步調用一個php頁面,並確保它已被加載

這將是一個不使用任何UIWebView的「幻影」調用,或者如果真的需要,隱藏的UIWebView,但我更願意避免這種情況。

你能幫我寫這個電話嗎?
並且一定要知道它是否已被加載?

我看到我應該使用NSURLConnection,但我有點失落。

你能幫我嗎?

回答

4

NSURLConection是非常好的異步加載解決方案。創建一個步驟很少。

1.設置你的NSURLConnection的

- (void)viewDidLoad { 
    // your code... 
    responseData = [[NSMutableData alloc] init]; 
    NSURL *url = [NSURL URLWithString:@"http://yourdomain.com/"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]]; 
} 

responseData是您NSMutableData伊娃。

2.實施委託方法

一)在這個方法中,我們將檢查HTTP狀態代碼

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    if ([response respondsToSelector:@selector(statusCode)]) { 
     int statusCode = [((NSHTTPURLResponse *)response) statusCode]; 
     if (statusCode >= 400) { 
      [connection cancel]; 
      NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:NSLocalizedString(@"Server returned status code %d",@""),statusCode] forKey:NSLocalizedDescriptionKey]; 
      NSError *statusError = [NSError errorWithDomain:NSHTTPPropertyStatusCodeKey code:statusCode userInfo:errorInfo]; 
      [self connection:connection didFailWithError:statusError]; 
     } 
    } 
} 

B)這將創建你的NSData組件

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [responseData appendData:data]; 
} 

Ç )處理成功的url連接

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    // do whatever you want using responseData as your server output 
} 

d)處理錯誤

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    // handle your error 
} 

可以使用[error userInfo]得到錯誤信息,並在UIAlertView中顯示它,例如。


因此,正如我說NSURLConnection的是非常好的解決方案,你也應該看看ASIHTTPRequest library。 :)

+0

@Kashiv:謝謝,我正在嘗試這個。我想知道,我怎麼知道NSData中返回的那種價值?它可以是任何比字符串... – Oliver 2011-05-07 19:37:25

+0

@Kashiv:NSHTTPPropertyStatusCodeKey si表示不贊成。我應該用什麼來代替。我正在尋找替代品,但我找不到合適的替代品。奇怪的是,即使表示不贊成,NSHTTPPropertyStatusCodeKey在編譯時不被識別。這是唯一的錯誤。 – Oliver 2011-05-07 21:58:28

+0

對不起。作爲_errorDomain_,您可以使用任何字符串,例如@「HTTPStatusCode」。請檢查這是否工作;) – akashivskyy 2011-05-07 22:10:14