2012-08-16 52 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