2009-04-01 4 views
9

Objective-C에서 프로그램을 작성 중이지만 웹 서버에 웹 요청을해야하지만 비동기 적으로 Mac에서 상당히 새로운 기술입니다. NSOperation (10.5에서 도입 된, 10.4 MAC에서 실행되지 않을 것이라고 가정하고 있습니까?)을 사용하거나 10.4에서 사용할 수있는 시스템 스레딩을 사용하도록 구현 된 경우이를 알고 있어야합니다.쿠키를 사용하는 Objective-C 비동기 웹 요청

새 스레드를 만들고 새 runloop을 만들어야하며, 쿠키 등을 사용하는 방법도 있습니다. 누군가가 저에게 작은 예제를 줄 수 있다면 큰 도움이 될 것입니다. 가능하다면이 샘플을 Mac 10.4에서도 실행하고 싶습니다.

답변

29

는 웹 사이트에 로깅 세션 ID 쿠키를 저장하고 향후 요청에 다시 제출의 전체 웹 애플리케이션 예제를 할 NSURLRequest 및 NSHTTPCookies를 사용하는 좋은 사례가있다. logix812으로

NSURLConnection, NSHTTPCookie

:

NSHTTPURLResponse * response; 
    NSError    * error; 
    NSMutableURLRequest * request; 
    request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"] 
              cachePolicy:NSURLRequestReloadIgnoringCacheData 
             timeoutInterval:60] autorelease]; 

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]); 

    // If you want to get all of the cookies: 
    NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]]; 
    NSLog(@"How many Cookies: %d", all.count); 
    // Store the cookies: 
    // NSHTTPCookieStorage is a Singleton. 
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil]; 

    // Now we can print all of the cookies we have: 
    for (NSHTTPCookie *cookie in all) 
     NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate); 


    // Now lets go back the other way. We want the server to know we have some cookies available: 
    // this availableCookies array is going to be the same as the 'all' array above. We could 
    // have just used the 'all' array, but this shows you how to get the cookies back from the singleton. 
    NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]]; 
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies]; 

    // we are just recycling the original request 
    [request setAllHTTPHeaderFields:headers]; 

    request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"]; 
    error  = nil; 
    response = nil; 

    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"The server saw:\n%@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]); 
+0

여기에 많은 감사합니다! – Hamy

+0

어떻게 비동기입니까 ??? –

+1

답장을 보내 주셔서 감사합니다. 질문이 있지만, 귀하는 [this] (http : //temp/gomh/authenticate.py? setCookie = 1) URL을 제공 한 첫 번째 URL과 두 번째 URL에 대해 서로 다른 URL을 지정했습니다. 하나의 http : // temp 등등. 내 앱에서 사용중인 웹 서비스가이 정보를 제공하지 않았기 때문에 쿠키의 URL을 어떻게 알 수 있습니까? – Hamid

18

비동기 요청의 경우 NSURLConnection을 사용해야합니다.

쿠키의 경우 NSHTTPCookieNSHTTPCookieStorage을 참조하십시오.

UPDATE :

아래의 코드 내 응용 프로그램 중 하나에서 실제 작업 코드입니다. responseData은 클래스 인터페이스에서 NSMutableData*으로 정의됩니다.

- (void)load { 
    NSURL *myURL = [NSURL URLWithString:@"http://stackoverflow.com/"]; 
    NSURLRequest *request = [NSURLRequest 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]; 
    // Show error message 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    // Use responseData 
    [responseData release]; 
    [connection release]; 
} 
+1

@Akash : NSURLConnection의 connectionWithRequest를 시도 했습니까? delegate : method? 미안하지만 질문에 NSURLConnection 또는 NSHTTPCookie에 대한 언급이 없습니다. 날 믿어, 내가 필요한 모든 것은 내가 준 링크에있다. –

+0

이미 그것을 사용했다, 그것은 거기에 어떤 샘플 코드로 그것을 할 수없는 비동기 요청을 할 다른 방법이 있어야합니다 생각 그래서 그것은 작동하지 않았다. 여기 내가 시도한 코드가 있습니다. http://stackoverflow.com/questions/706355/whats-wrong-on-following-urlconnection –

+0

@Akash : NSURLConnection이 가장 쉬운 방법입니다. 샘플 코드를 게시하겠습니다. –

3

나는 같은 방법으로 쿠키를 가져올 수 있어요 :

NSArray* arr = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString: @"http://google.com" ]]; 

이것은뿐만 아니라 비동기 요청에 대해 잘 작동합니다.

관련 문제