使用ASIFormDataRequest同步的多个POST请求

时间:2014-09-09 01:06:38

标签: ios post asihttprequest

基本上我的应用程序将从数据库中检索数据数组并将其上传到服务器(一次一个/一个接一个)。我希望在其中一个数据无法上传时停止所有请求(请查看评论)。

代码:

// 0 means need to upload to server
NSString *condition = [NSString stringWithFormat:@"isUploaded=\"0\""];
// array of ID on my database to be uploaded
NSArray *arrayOfID = [Registered distinctValuesWithAttribute:@"registeredID" predicate:[NSPredicate predicateWithFormat:condition]];

// loop every index and upload it to server
for (int i=0; i<arrayOfID.count && !isBreak; i++) {
            // get the entity using ID
            NSString *condition = [NSString stringWithFormat:@"registeredID=\"%@\"",[arrayOfID objectAtIndex:i]];
            Registered *entity = [Registered getWithPredicate:[NSPredicate predicateWithFormat:condition]];
            if (entity) {
                __weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
                [self setRequest:request withEntity:entity]; // set delegate,POST,etc.
                [request setCompletionBlock:^{
                        // returns dictionary (success/failed)
                        NSDictionary *dict = [[request responseString] JSON];
                        if ([[dict valueForKey:@"status"] isEqualToString:@"success"]) {
                            // set IsUploaded to 1 after successful upload to server
                            [entity setIsUploaded:[NSNumber numberWithInt:1]];
                            [Registered commit];
                            // Any necessary ideas that would make my code better 
                            // and continue the POST request and proceed to the next entity???  
                        }
                        else {
                            // I want to cancel all the request here and get out to this loop
                            }
                 }];
                 [request setFailedBlock:^{
                       // I want to cancel all the request here and get out to this loop
                 }];
                 // start startSynchronous
                 [request startSynchronous];

        } else {
            [GlobalMethods ShowAlertView:@"Database Error" message:@"Please try again later"];
            isBreak=YES;
        }

}

1 个答案:

答案 0 :(得分:0)

您可以稍微调整一下代码并使用提供的ASINetworkQueue类。从the documentation开始,如果队列中的一个请求失败,则默认情况下会自动取消其余请求。

您可以使用break语句立即退出循环。但是,因为回调是异步的,所以在故障块中放置一个将不会产生你正在寻找的效果...假设故障块是针对服务器响应而不是API本身的某些东西而触发的,那个循环将会完成并触发所有请求 - 并且封闭方法将返回 - 很久之前您的任何请求都有时间从服务器返回并调用其故障块(这是网络代码,毕竟)。因此,您无法使用故障块来中断在循环中创建其他请求;这不是异步调用的工作原理。