gpt4 book ai didi

ios - 在获取 JSON 时在 iOS 中使用 spinKit 显示微调器

转载 作者:行者123 更新时间:2023-11-29 12:00:40 25 4
gpt4 key购买 nike

我想做的是,单击一个按钮,我使用 AFNetworking pod 获取数据。我想要的是在获取数据后我想显示 NSLog(@"/n/nAfter fetching"); 但它在 json 数据之前出现。

这是我在 Button 的 IBAction 中编写的代码。

dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
//Load the json on another thread

NSURL *url = [NSURL URLWithString:finalURL];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response,id responseObject, NSError *error) {

if (error) {
NSLog(@"\n Error --> %@",error);
}
else{
jsonDictionary = (NSDictionary*) responseObject;
NSLog(@"/n Data :: %@",jsonDictionary);
}
}];
[dataTask resume];

});

NSLog(@"/n /nAfter fetching");

请提供一个很好的方法,如果我做错了,请纠正我。谢谢。

最佳答案

作为 AFURLSessionManager 进行异步操作。完成后你会得到数据

dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
//Load the json on another thread
[self startSpinner];
NSURL *url = [NSURL URLWithString:finalURL];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response,id responseObject, NSError *error) {
[self stopSpinner];

if (error) {
NSLog(@"\n Error --> %@",error);
}
else{

NSLog(@"/n /nAfter fetching"); //this is where you receive data
jsonDictionary = (NSDictionary*) responseObject;
NSLog(@"/n Data :: %@",jsonDictionary);
}
}];
[dataTask resume];

});

如果你想使用 URLSession 进行同步操作,下面的方法将帮助你

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request  
returningResponse:(__autoreleasing NSURLResponse **)responsePtr
error:(__autoreleasing NSError **)errorPtr {
dispatch_semaphore_t sem;
__block NSData * result;

result = nil;

sem = dispatch_semaphore_create(0);

[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (errorPtr != NULL) {
*errorPtr = error;
}
if (responsePtr != NULL) {
*responsePtr = response;
}
if (error == nil) {
result = data;
}
dispatch_semaphore_signal(sem);
}] resume];

dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

return result;
}

关于ios - 在获取 JSON 时在 iOS 中使用 spinKit 显示微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37155418/

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