2016-10-27 4 views
0

NSURLConnectionDelegate 메소드를 구현하는 서비스 API 클래스와 비슷합니다. 이 메소드 중 일부는 사용되지 않으며 Apple은 이제 NSURLSession을 사용하도록 제안합니다. 호출 클래스가 구현하고 응답을 받으면 실행될이 서비스 API 자체 델리게이트를 만들었습니다. NSURLSession을 사용하는 동안 비슷한 작업을 수행 할 수있는 방법을 찾고 있습니다. 있는 NSURLConnection와NSURLConnection을 NSURLSession으로 변환하는 동안 컨트롤러에 응답을 전달합니다.

내 존재하는 물건 : ServiceAPI 구현 파일에서

@class ServiceAPI; 
@protocol ServiceAPIDelegate <NSObject> 

- (void)getResponseData:(NSData *)responseData; 

@end 

@interface ServiceAPI : NSObject<NSURLCoDelegate> 
- (void)httpServiceRequest:(NSMutableURLRequest *)serviceRequest; 
@property (nonatomic, weak) id <ServiceAPIDelegate> delegate; 
@end 

:

- (void)httpServiceRequest:(NSMutableURLRequest *)serviceRequest { 
    //[[NSURLSession sharedSession] dataTaskWithRequest:serviceRequest] resume]; 
    self.requestConnection = [NSURLConnection connectionWithRequest:serviceRequest delegate:self]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    [self.delegate getResponseData:self.responseData sender:self]; 
} 

클래스를 만드는 요청 받고 응답 :

@interface CallingController : UITableViewController<ServiceAPIDelegate> 
@end 

구현 파일 CallingController : 나는 NSURLSession를 사용하는 동안 호출 클래스 그냥있는 NSURLConnection 같은 응답 방법을 처리하도록 할 방법

- (void)getResponseData:(NSData *)responseData { 
    // Do something with response. 
} 

. NSURLSession을 읽는 것은이 같은 완료 핸들러 뭔가를 사용하여 함께 처리 요청 및 응답 보이지만 :

NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    NSLog(@"%@", json); 
}]; 
나는 여전히 통화를 할 수있는 API를 서비스에 대한 요청을 전달할 것입니다 서비스 API 클래스와 내 컨트롤러를 갖고 싶어

응답이 되돌아 오면 컨트롤러로 전달됩니다. NSURLSession을 사용하는 동안 컨트롤러에 응답을 전달하려면 어떻게해야합니까?

답변

0

뭔가 : 구현에서

@class ServiceAPI; 

    @protocol ServiceAPIDelegate <NSObject> 

    - (void)getResponseData:(NSData *)responseData; 

    @end 

    @interface ServiceAPI : NSObject<NSURLSessionDelegate> 
    - (void)httpServiceRequest:(NSMutableURLRequest *)serviceRequest; 
    @property (nonatomic, weak) id <ServiceAPIDelegate> delegate; 
    @end 

- (void)httpServiceRequest:(NSMutableURLRequest *)serviceRequest { 
    NSURLSession *session = [NSURLSession sharedSession]; 
    NSURLSessionDataTask *downloadTask = 

    [session dataTaskWithRequest:serviceRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     [self.delegate getResponseData:data sender:self]; 

    }]; 

    [downloadTask resume]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    // no use 
} 
0

완료 블록없이 NSURLSessionDataTask을 초기화하여 원하는 것을 얻을 수 있습니다. 그런 식으로 대신 델리게이트 메서드를 호출합니다. 예를 들어

:

NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"]]; 
[dataTask resume]; 

NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask 
           didReceiveResponse:(NSURLResponse *)response 
            completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler; 

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask 
            didReceiveData:(NSData *)data; 

는 또한 요청이 완료 될 때 알고 NSURLSessionTaskDelegate을 구현 구현합니다. 이 같은

/* Sent as the last message related to a specific task. Error may be 
* nil, which implies that no error occurred and this task is complete. 
*/ 
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task 
          didCompleteWithError:(nullable NSError *)error;