2012-08-16 114 views
0

我正在做一个应用程序,我必须调用一些web服务。我选择与AFNetworking合作。IOS5 - AFNetworking处理请求

我跟着图书馆提供的Twitter示例。除了我在通知栏中永久存在小的“处理循环”(参见下图)之外,一切运作良好。

iPhone topbar

下面的代码我有我的要求:

- (id)initWithAttributes:(NSDictionary *)attributes 
{ 
    self = [super init]; 
    if (!self) { 
     return nil; 
    } 

    _name = [attributes valueForKeyPath:@"name"]; 
    return self; 
} 

+ (void)itemsListWithBlock:(void (^)(NSArray *items))block 
{ 
    NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults]; 
    NSDictionary *user    = [defaults objectForKey:@"user"]; 
    NSDictionary *company   = [defaults objectForKey:@"company"]; 

    NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary]; 

    /* 
    ** [ Some stuff to set the parameters in a NSDictionnary ] 
    */  

    MyAPIClient *client = [MyAPIClient sharedClient]; 
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount]; 

    NSURLRequest *request = [client requestWithMethod:@"POST" path:@"getMyList" parameters:mutableParameters]; 

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     NSMutableArray *mutableItems = [NSMutableArray arrayWithCapacity:[JSON count]]; 
     for (NSDictionary *attributes in JSON) { 
      ListItem *item = [[ListItem alloc] initWithAttributes:attributes]; 
      [mutableItems addObject:item]; 
     } 
     if (block) { 
      block([NSArray arrayWithArray:mutableItems]); 
     } 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){ 
     [[[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil] show]; 
     if (block) { 
      block(nil); 
     } 
    }]; 
    [operation start]; 
} 

这是否意味着我的要求是不是完了?我真的不明白我在这里做错了什么...

如果有人可以帮助,我会很感激。谢谢。

回答

5

不要致电[[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];这增加活动计数1和[operation start];也会称之为。现在活动计数是2,并且在操作完成时会减少。但是,既然你叫incrementActivityCount它将把它带回1和不为0

就叫[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];一次,例如将其放置在您的应用程序appDeletage的application:applicationdidFinishLaunchingWithOptions:方法。


此外,我会建议将操作添加到NSOperationQueue,而不是只是调用启动它。

+0

谢谢你的解决方案,并为队列提示,我会研究这个! – 2012-08-16 10:29:45