2011-12-15 4 views
21

반환 값 1 또는 0 만 반환하는 방법을 알고 싶습니다. 다시 URL 요청에서 비동기 적으로 반환합니다.비동기 URL 요청을 보내는 방법은 무엇입니까?

현재 나는이 방법으로 그것을 수행

이 내가 다시 URL에서 회신을 받았는데까지, 그러나 내 주 스레드를 차단하고 작동
 NSString *UTCString = [NSString stringWithFormat:@"http://web.blah.net/question/CheckQuestions?utc=%0.f",[lastUTCDate timeIntervalSince1970]]; 
     NSLog(@"UTC String %@",UTCString); 
     NSURL *updateDataURL = [NSURL URLWithString:UTCString]; 
     NSString *checkValue = [NSString stringWithContentsOfURL:updateDataURL encoding:NSASCIIStringEncoding error:Nil]; 
     NSLog(@"check Value %@",checkValue); 

, 내가 그것을 설정하는 방법은 그것을 할 수 있도록 메인 스레드 대신 다른 스레드?

편집 : 나는이 내 기능을 upcalling과 끝 답변 , 그것은 잘 작동합니다 :)

[self performSelectorInBackground:@selector(shouldCheckForUpdate) withObject:nil]; 
+5

에서 iOS 5로, 당신이 사용할 수있는'+ (무효) sendAsynchronousRequest : (NSURLRequest *) 요청 큐 (NSOperationQueue *) 큐 completionHandler : (무효 (^) (NSURLResponse *을 NSData *, NSError *)) handler'를 대신 사용하여 위임 객체를 만드는 것보다 간단한 요청에 대해 쉽고 명확합니다. 나중에이 방법을 보여주는 답을 작성하려고합니다. –

+1

@MarkAmery 귀하의 답변을 보는 것이 좋을 것입니다. 'sendAsynchronousRequest'의 간단한 예제를 찾는 데 어려움을 겪고 있습니다. –

답변

28

당신은 NSURLConnection 클래스

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 

를 사용하고 응답 및 위임 방법을 사용하여 오류를 처리 할 수 ​​있습니다.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

당신은있는 NSURLConnection

의 구현
  • How To Use iOS NSURLConnection By Example
  • 편집

    • Apple docs: Using NSURLConnection 을 찾을 수 있습니다 NSURLConnection가 애플에 의해 제공되어 있지만 URL 요청을 배치의 이상 권장 방법입니다. 하지만 AFNetworking 라이브러리는 매우 시간을 절약하고 구현하기 쉽고 타사 구현으로 강력하면서도 간단합니다. 시도 해봐야합니다.

    +1

    쿠키 값을 얻기 위해 어떤 메소드를 사용해야합니까 ?? – kAnNaN

    5

    사용 NSURLConnection 및 귀하의 요청을합니다. 비동기

    + connectionWithRequest:delegate: 
    – initWithRequest:delegate: 
    – initWithRequest:delegate:startImmediately: 
    – start 
    

    애플 개발자 API 참조 설명서에서 NSURLConnection 클래스를 확인 데이터 로딩 데이터 기적

    + sendSynchronousRequest:returningResponse:error: 
    

    로드

    : 은 다음 당신은있는 NSURLConnection의 방법과 동기 또는 비동기 연결을 시작할 수 있습니다.

    +0

    여기에 링크가 있습니다 : http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html – samfisher

    26

    이 시도 :

    .H :

    NSMutableData *responseData; 
    

    하는 .m : 아이폰 OS 엑스 코드 문서라는 LazyTableImages의 예입니다

    - (void)load 
    { 
        NSURL *myURL = [NSURL URLWithString:@"http://www.example.com"]; 
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; 
    
        [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    } 
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
    { 
        responseData = [[NSMutableData alloc] init]; 
    } 
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
    { 
        [responseData appendData:data]; 
    } 
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
    { 
        [responseData release]; 
        [connection release]; 
        [textView setString:@"Unable to fetch data"]; 
    } 
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
    { 
        NSLog(@"Succeeded! Received %d bytes of data",[responseData 
                    length]); 
        NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease]; 
    } 
    
    +0

    나는 단지 1이나 0의 답장이 필요하다. 너무 많은가? – Desmond

    +0

    @Maulik "스마트 개발자"방을 추가하십시오. – MinuMaster

    +0

    @Maulik, 내 하루를 구 했으니 큰 감사합니다! – DeZigny

    2

    . 이것은 비동기 URL뿐만 아니라 스크롤이 멈춘 후 화면에 표시된 UITableView 셀에 비동기 이미지로드를 수행합니다. 프로토콜, 비동기 데이터 처리 등의 우수 사례.

    3

    뻔뻔스럽게 https://gist.github.com/knmshk/3027474에서 복사하십시오. 모든 크레딧은 https://gist.github.com/knmshk입니다.

    xmlData = [[NSMutableData alloc] init]; 
    NSURL *url = [NSURL URLWithString: 
    @"http://forrums.bignerdranch.com/smartfeed.php?" 
    @"limit=NO_LIMIT&count_limit20&sort_by=standard&" 
    @"feed_type=RSS2.0&feed_style=COMPACT"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    //connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 
    NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 
    [NSURLConnection sendAsynchronousRequest:request 
                queue:queue 
             completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ 
              if (error) { 
               xmlData = nil; 
               NSLog(@"error:%@", error.localizedDescription); 
              } 
              [xmlData appendData:data]; 
             }]; 
    
    관련 문제