我有一些问题,了解如何使用完成块调用方法为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)];
}
说真的,你可以改变你的问题的标题? – gnasher729 2014-09-25 23:13:23
@ gnasher729,你对他的头衔有“异议”?我没有提出你的反对意见。 :) – 2014-09-26 00:46:14