2014-09-25 2 views
-2

완료 블록을 사용하여 메서드를 NSURLSessionTask로 호출하는 방법을 이해하는 데 몇 가지 문제가 있습니다. 어떻게하면 오류없이 getForecastAndConditionsForZipCode 메서드를 제대로 호출하는지 궁금합니다. 고맙습니다!Objective-C 완료 블록

Api.h :

typedef void (^WeatherAPICompletionBlock)(BOOL success, NSDictionary *result, NSError *error); 

- (NSURLSessionDataTask *)getForecastAndConditionsForZipCode:(NSString *)zipCode withCompletionBlock:(WeatherAPICompletionBlock)completionBlock; 

Api.m

- (NSURLSessionDataTask *)getForecastAndConditionsForZipCode:(NSString *)zipCode withCompletionBlock:(WeatherAPICompletionBlock)completionBlock 
{ 
if (!self.APIKey) { 
    NSAssert(NO, @"API Key not set", nil); 
    completionBlock(NO, nil, [self missingAPIKeyError]); 
    return nil; 
} 

if (![NSThread isMainThread]) { 
    NSAssert(NO, @"API client method must be called on the main thread", nil); 
    completionBlock(NO, nil, [self genericError]); 
    return nil; 
} 

// Create the path 
NSString *pathString = [NSString stringWithFormat:@"/api/%@%@/q/%@.json", self.APIKey, kWeatherAPIConditionsPath, zipCode]; 

// To avoid a retain cycle 
__weak __typeof(self)weakSelf = self; 

// Start the request 

return [self GET:pathString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) { 
if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]] || [responseObject count] == 0) { 
     DLog(@"Invalid responseObject: %@", responseObject); 
     completionBlock(NO, nil, [weakSelf genericError]); 
     return; 
    } 
    completionBlock(YES, responseObject, nil); 
} failure:^(NSURLSessionDataTask *task, NSError *error) { 
    DLog(@"Error with getForcastForLocation response: %@", error); 
    completionBlock(NO, nil, error); 
}]; 

}

ViewController.m (여기 내가 getForecastAndConditionsForZipCode 방법

를 호출하는 방법을 이해하지 못하는 곳이다

import "Api.h"

- (IBAction)runApi:(UIButton *)sender { 

    WeatherAPIClient *weatherApiClient = [[WeatherAPIClient alloc] init]; 

    NSURLSessionDataTask *test = [weatherApiClient getForecastAndConditionsForZipCode:@"55345" withCompletionBlock:^(YES, result, error)]; 

} 
+1

진지하게 질문 제목을 변경 할 수 있습니까? – gnasher729

+0

@ gnasher729, 그의 제목에 "반대"가 있습니까? 나는 당신의 이의 제기에 실패합니다. :) –

답변

2

Xcode에서 코드 완성을 사용하면이 작업을 간단하게 수행 할 수 있습니다.

유형 :

NSURLSessionDataTask *test = [weatherApiClient getForecast 

와 일치하는 메소드 이름을 선택합니다. 그런 다음 withCompletionBlock: 뒤에 자리 표시 자로 이동하고 return 키를 누릅니다.

NSURLSessionDataTask *test = [weatherApiClient getForecastAndConditionsForZipCode:@"55345" withCompletionBlock:^(BOOL success, NSDictionary *result, NSError *error) { 
}]; 

지금 당신은 중괄호 사이의 부분에 작성해야합니다 : 마술 당신과 함께 종료됩니다. 처리가 완료 될 때 호출 할 블록입니다. success, resulterror에 대한 값이 제공됩니다. getForecastAndConditionsForZipCode:withCompletionBlock:의 구현이 완료 블록을 가정하지 않아야에 전달이 완료 블록에 대한 모든 호출 보호하십시오 - BTW

NSURLSessionDataTask *test = [weatherApiClient getForecastAndConditionsForZipCode:@"55345" withCompletionBlock:^(BOOL success, NSDictionary *result, NSError *error) { 
    if (success) { 
     // do something with result 
    } else { 
     NSLog(@"Uh oh - error getting forecast: %@", error); 
    } 
}]; 

:

if (completionBlock) { 
    completionBlock(YES, someResult, nil); // or whatever values you need to send 
} 

이 코드를 당신은 아마 같은 것을 원하는. 누군가 전화를 걸면 앱이 다운되지 않도록하십시오.

NSURLSessionDataTask *test = [weatherApiClient getForecastAndConditionsForZipCode:@"55345" withCompletionBlock:nil]; 
+0

그것은 본질적으로 내가 한 일입니다. 유일한 문제는 xcode를 사용하여 입력 할 수 없으므로 실제로 수동으로 입력해야합니다. 고마워요, 일할 수 있어요? – jKraut