2010-07-24 6 views
0

내 응용 프로그램은 특정 URL로 10 초마다 서버에서 요청을 보내고 URL의 일부 속성을 변경 한 다음 요청을 "updateView"라는 다른보기 또는 다른 네트워크 오류가 발생하여 오류가 표시됩니다. 첫 번째 부분은 잘 작동하지만 Wi-Fi로 전환하면 앱이 다운됩니다. 어떻게이 문제를 해결하고 다양한 오류를 표시합니까? 미리 감사드립니다 !! 현재 당신이 stringWithContentsOfURL를 사용하는NSURL 오류 처리

+ (id)stringWithContentsOfURL:(NSURL 
*)url encoding:(NSStringEncoding)enc error:(NSError **)error 

전화를 1.Changing :

- (void)serverUpdate{ 
CLLocationCoordinate2D newCoords = self.location.coordinate; 

gpsUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://odgps.de/chris/navextest?objectid=3&latitude=%2.4fN&longitude=%2.4fE&heading=61.56&velocity=5.21&altitude=%f&message=Eisberg+voraus%21", newCoords.latitude, newCoords.longitude, self.location.altitude]]; 

self.pageData = [NSString stringWithContentsOfURL:gpsUrl]; 


[updateView.transmissions insertObject:pageData atIndex:counter]; 
if (counter == 100) { 
    [updateView.transmissions removeAllObjects]; 
    counter = -1; 
} 
counter = counter + 1; 



    [updateView.tableView reloadData]; 
self.sendToServerSuccessful = self.sendToServerSuccessful + 1; 
[self.tableView reloadData]; 
} 

답변

3

먼저, stringWithContentsOfURL:으로 전화를 걸 때 네트워크 작업이 완료 될 때까지 기다리는 동안 주 스레드를 차단합니다. 네트워크가 느리거나 도달 할 수없는 경우 앱이 다운 된 것처럼 보일 것입니다.

둘째, stringWithContentsOfURL:는 사용되지 않으며 당신은 심지어 여전히 블록 메인 쓰레드하지만, 대신를 사용한다 : 당신은 메인 스레드를 차단하지 않고 데이터를 다운로드 할 수있는 NSURLConnection을 사용한다

self.pageData = [NSString stringWithContentsOfURL:gpsURL encoding:NSUTF8StringEncoding error:nil]; 

. URL에서 NSURLRequest을 작성하고 URL 연결을 시작하는 [NSURLConnection connectionWithRequest:request delegate:self];으로 전달하십시오.

는 여기에있는 NSURLConnection 위임에 대한 몇 가지 코드입니다 :

- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response { 
    if ([response isKindOfClass: [NSHTTPURLResponse class]]) { 
     statusCode = [(NSHTTPURLResponse*) response statusCode]; 
     /* HTTP Status Codes 
      200 OK 
      400 Bad Request 
      401 Unauthorized (bad username or password) 
      403 Forbidden 
      404 Not Found 
      502 Bad Gateway 
      503 Service Unavailable 
     */ 
    } 
    self.receivedData = [NSMutableData data]; 
} 

- (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)data { 
    [self.receivedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { 
    // Parse the received data 
    [self parseReceivedData:receivedData]; 
    self.receivedData = nil; 
} 

- (void)connection:(NSURLConnection *)aConnection didFailWithError:(NSError *)error { 
    statusCode = 0; // Status code is not valid with this kind of error, which is typically a timeout or no network error. 
    self.receivedData = nil; 
} 
+0

큰 난이 대단히 감사합니다 많은 도움이 될 것 같아요! 하지만 내가 상태 코드를 표시 할 수 있기 때문에 이전에 설정 한 속성을 가진 URL (요청 URL)을 표시하고 싶다면 어떻게해야합니까? –

+0

그리고 어떤 유형이 "statusCode"변수입니까? –

+0

statusCode는 int입니다. 요청을 표시하려면 응답 형식에 따라 다르지만 UIWebView가 가장 잘 작동합니다. – lucius

0

변경 다음을 수행하십시오 여기 내 코드 (이 매 10 초마다 호출되는 방법입니다)입니다.

2.이 호출이 반환하는 nil 값을 처리합니다. URL 실행에 오류가 있으면 호출은 nil 객체를 반환합니다. 현재 구현에서는 개체 API 반환을 추가하는 것입니다. (이것이 사용자의 충돌의 원인 일 수 있다고 생각합니다.)