搜尋此網誌

2012年9月12日 星期三

AFNetworking使用範例


直接使用


NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlstr]];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
      
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,NSError *error, id JSON) {
        NSLog(@"error:%@,response:%@",error,response);
        
    }];
[operation start];


使用block


Film.m

+ (void)getFilmsTypeWithBlock2:(void (^)(NSArray *films))block{
    MyManager *sharedManager = [MyManager sharedManager];
    
    [[AFVL2APIClient sharedClient] getPath:@"Vl2api.do?opt=getFilmTypeUnderFilmType" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
       
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[JSON count]];
        for (NSDictionary *attributes in JSON) {
            Film *film = [[Film alloc] initWithAttributes:attributes];
            [mutableArray addObject:film];
        }
        
        if (block) {
            block([NSArray arrayWithArray:mutableArray]);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil] show];
#else
        [[NSAlert alertWithMessageText:NSLocalizedString(@"Error", nil) defaultButton:NSLocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:[error localizedDescription]] runModal];
#endif
        if (block) {
            block(nil);
        }
    }];
    
}

viewController.m
[FilmType getFilmsTypeWithBlock:^(NSArray *films) {
        if(films){

        }
    }];




沒有留言:

張貼留言