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。 :)
@Kashiv:謝謝,我正在嘗試這個。我想知道,我怎麼知道NSData中返回的那種價值?它可以是任何比字符串... – Oliver 2011-05-07 19:37:25
@Kashiv:NSHTTPPropertyStatusCodeKey si表示不贊成。我應該用什麼來代替。我正在尋找替代品,但我找不到合適的替代品。奇怪的是,即使表示不贊成,NSHTTPPropertyStatusCodeKey在編譯時不被識別。這是唯一的錯誤。 – Oliver 2011-05-07 21:58:28
對不起。作爲_errorDomain_,您可以使用任何字符串,例如@「HTTPStatusCode」。請檢查這是否工作;) – akashivskyy 2011-05-07 22:10:14