NSURLConnection と 500 Server Error
NSURLConnectionのデレゲートにconnection:didFailWithError: がありますが、500番などのサーバエラーなどの時、NSURLConnectionはそのDelegateMethodを呼びません。
困った事に、connection:didReceiveResponse: でステータスコードをチェックする必要があります。下記のような感じ*1。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 500 エラーなどでないかチェック。 // エラーの場合、アラートを表示させる 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]; // 無理矢理。 // iPhoneでは、何故か知らないが、NSHTTPPropertyStatusCodeKeyが定義されてない。 NSError *statusError = [NSError errorWithDomain:@"NSHTTPPropertyStatusCodeKey" code:statusCode userInfo:errorInfo]; // エラーを呼ぶ [self connection:connection didFailWithError:statusError]; } }
参考
・Dan Wood: The Eponymous Weblog (Archives) | by Dan Wood, Karelia Software
・iphone - Testing use of NSURLConnection with HTTP response error statuses - Stack Overflow
*1:少し変更、iPhoneでは、NSURLで定義されてるはずのNSHTTPPropertyStatusCodeKeyがなぜか定義されていない。