gpt4 book ai didi

ios - GCD dispatch_sync没有按顺序执行

转载 作者:行者123 更新时间:2023-12-01 18:58:55 28 4
gpt4 key购买 nike

我有一种方法可以帮助我将本地standardUserDefaults与Web服务同步。首先,我需要确保数据已成功同步,然后才能让该方法返回。我目前正在努力解决的问题是,我无法让GCD按特定顺序执行并完成任务:首先 POST到Web服务,然后 POST到返回。

问题在于第二个dispatch_sync任务首先完成执行,然后出现第一个dispatch_sync任务。如何确保执行按计划进行?由于NSURLSessionDataTask,这是否是特殊情况?

非常感谢!

-(void) syncLocalStorageToMMUsersDB:(void(^)(bool success))handler
{
__block bool fb_sync_success = 0;

dispatch_queue_t requestQueue = dispatch_queue_create("com.micromorts.request", DISPATCH_QUEUE_SERIAL);


//if logged in with Facebook, then sync it
if ([_defaults stringForKey:MMFBIdPrefsKey]) {
// Start NSURLSession
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

// POST parameters
NSURL *url = [NSURL URLWithString:@"http://THE.URL.GOES.HERE"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString *params = [POST PARAMS GO HERE];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

// NSURLSessionDataTask returns data, response, and error

NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Handle response
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger statusCode = [httpResponse statusCode];
if(error == nil) {
if (statusCode == 404) {
NSLog(@"MMAuth.m :: syncLocalStorageToMMUsersDB FB :: FB User not found");
fb_sync_success = false;

} else if (statusCode == 200) {
NSLog(@"MMAuth.m :: syncLocalStorageToMMUsersDB FB :: Successfully synced ");
fb_sync_success = true;

} else {
NSLog(@"MMAuth.m :: syncLocalStorageToMMUsersDB FB :: Sync fail ");
fb_sync_success = false;
}
}
}
];
//This should finish EXECUTING first
dispatch_sync(requestQueue, ^{
[dataTask resume];
});
}

//This should finish EXECUTING second
dispatch_sync(requestQueue, ^{

if (fb_sync_success){
NSLog(@"SUCCESS");
} else {
NSLog(@"FAILED");
}

});
}

最佳答案

如果对[dataTask resume];的调用是异步的,则该dispatch_sync()将在-resume执行后立即返回,然后随后的dispatch_sync()将入队并在之后(但在加载数据之前)立即执行。

将您的SUCCESS / FAILED逻辑移到完成处理程序块中;这就是为什么存在完成处理程序的原因。

关于ios - GCD dispatch_sync没有按顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com