IOS AFNet Working and Thread Synchronization

Keywords: iOS network

In iOS development, the data of pages is not acquired through an interface. Sometimes it is necessary to acquire data from multiple interfaces of servers, and then update the pages. Sometimes it is necessary to acquire data from one interface and then acquire data from other interfaces.

The source framework AFNetWorking is a powerful third-party framework in common use. We can use the combination of AFNetWorking and GCD to fulfill the above two requirements.

(1) After obtaining multiple interface data, create or reload UITableview. Put the operation of network data acquisition into the thread group. When each thread is finished, the new page is rooted in the main thread.

For example:

Data for 1 and 2 come from two different interfaces. Project requirements, load together. Then we can use thread groups to solve this problem.

The code is as follows:

#pragma mark - Get the user's receiving address and list of goods into the queue
-(void)getInitInfoFromServer
{
    dispatch_group_t group = dispatch_group_create();


    // 2 Setting Head
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];
    _manager.requestSerializer = [AFJSONRequestSerializer serializer];


    GCToken *token = [GCTokenManager getToken];
    NSString *tokenStr = [GCTokenManager getFullToken:token];
    [_manager.requestSerializer setValue:tokenStr forHTTPHeaderField:@"Authorization"];

    //Enter group
    dispatch_group_enter(group);
    // Get the default
    NSString *addressStr = @"http://XXXXXXXXXXXXXXXXX";
    [_manager GET:addressStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSMutableArray *dataDics = responseObject[@"data"];

        _defaultAddressModel = [GCAddressModel mj_objectWithKeyValues:dataDics];

        dispatch_group_leave(group);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failed to get the list of receipt addresses----%@",error);
        dispatch_group_leave(group);
    }];


    dispatch_group_enter(group);
    NSString *shoppingCartUrl = @"http://XXXXXXXXXXXX";
    [_manager GET:shoppingCartUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSMutableArray *dataDics = responseObject[@"items"];

        _shoppingCartArrs = [GCShoppingCartProductModel mj_objectArrayWithKeyValuesArray:dataDics];


        dispatch_group_leave(group);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure to obtain shopping cart data----%@",error);
        dispatch_group_leave(group);
    }];


    dispatch_group_notify(group, dispatch_get_main_queue(), ^(){
        //Initialize or update pages
        [self initAllView];
    });

}

(2) After acquiring the data of one interface, the data of other interfaces are acquired according to the data obtained.
One requirement is to modify the user's receiving address, save and use it, save the receiving address is an interface, and then get the receiving address update page. There are two ways to do this. The first is to modify the model in the callback block and jump to the corresponding page after the successful storage of the receiving address. The second one is that after modifying the interface of the model and modifying the model successfully, the interface to get the receiving address is called to get the receiving address, and the next operation is carried out.
If the project requires two interactions with the server, we can still use thread groups for simple solutions.

There are specific needs:
Click on the receiving address, set the receiving address to the default receiving address, and re-update the page.

After the default receiving address is set successfully, the list of receiving addresses is obtained directly in the callback function and the page is updated. After these column operations are completed, dispatch_group_notify(group, dispatch_get_main_queue() is used for other desired operations, similar to notification.

The code is as follows:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    _HUD.labelText = @"One moment please";

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_enter(group);
    _selectedIndex = (int)indexPath.row;
    // Get a connection
    GCAddressModel *model = _addressArrs[indexPath.row];
    NSString *defaultAddressStr = [[NSString alloc]initWithFormat:@"http://XXXXXXXX;

    [_manager POST:defaultAddressStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSString *addressStr = @"http://XXXXXXXX";
        [_manager GET:addressStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSMutableArray *dataDics = responseObject[@"data"];

            _addressArrs = [GCAddressModel mj_objectArrayWithKeyValuesArray:dataDics];


            [_mainTableView reloadData];


        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failed to get address--%@",error);
        }];

        dispatch_group_leave(group);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_group_leave(group);
        NSLog(@"Failed to set default receiving address");

    }];




    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [_HUD removeFromSuperview];
        _HUD  = nil;
        // Send notifications
        [[NSNotificationCenter defaultCenter]postNotificationName:@"editDefaultAddress" object:nil];

    });

}

Posted by planethax on Sun, 30 Jun 2019 13:08:56 -0700