gpt4 book ai didi

ios - 多个 iOS GET 请求(动态请求数)

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

我正在使用在线 API 来检索随机名言。在我的代码中,我使用:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urloftheapi]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:@"GET"];


NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[connection release];

但是,我希望它能引入不止一个引用。该 API 不包含多引号功能,因此我需要运行多个 NSMutableURLRequest 才能获得全部。但是,由于它可能是 1 个请求,也可能是多个请求,所以我不确定在代码中实现它的最佳方法。想法?

最佳答案

根据 API 的设置方式,您可以执行一个请求来获取引号列表(即 quoteID 的数组/字典等)。从那里您可以循环遍历您获得的所有 quoteID 并执行特定请求以通过 quotes ID 属性获取每个报价。

如果没有 API 的描述,几乎不可能给你一个准确的答案,但我刚才描述的是这些类型问题的一般方法。

1) 请求获取报价列表(只是他们的主键/唯一 ID)

2) 遍历上一个请求中的所有 id,并发出特定请求以通过哪个 id 获取报价。

使用 AFNetworking 库,它看起来像这样。请记住,请求是在不同的线程中处理的,因此您可能需要设置一个 NSNotification 来跟踪您何时完成获取每个单独的报价和/或跟踪报价总数(外部循环)和当前个人引用您所请求的(内部循环)。通过比较这两个计数,您可以知道何时完成。

NSMutableArray *allQuotes = [[NSMutableArray alloc] init];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *url = @"www.whatever.com/api/quotes";
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *quoteList = (NSArray *)responseObject;
for(NSString *quoteID in quoteList)
{
[manager GET:url parameters:@{@"quoteID":quoteID} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[allQuotes addObject:responseObject];
[NSNotificationCenter defaultCenter] postNotificationName:@"FINISHED_GETTING_QUOTE" object:allQuotes];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Handle failure here...
}];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Handle failure here...
}];

-(void)finishedGettingQuotes:(NSNotification *)notification
{
if(currentRequest == totalRequests)
{
NSMutableArray *temp = notification.object;
}
}

关于ios - 多个 iOS GET 请求(动态请求数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26103184/

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