【问题标题】:Pokeapi and getting resource_uriPokeapi 和获取 resource_uri
【发布时间】:2015-11-30 03:07:24
【问题描述】:

所以我使用 AFNetworking 和 pokeapi 来获取 pokemon 列表。我可以让 tableview 加载,标题是 pokemon 的名称。但我希望字幕成为类型。所以我将基数设置为#define pokeApiBaseURL [NSURL URLWithString: @"http://pokeapi.co/"]

这是我的请求的样子。我创建了一个数组,它为我提供了需要解析并获取类型和所有其他 pokemon 信息的 url 的下半部分。但我似乎无法弄清楚如何让 baseURL 和 resource_uri 创建一个新的 url 供我解析。

NSString *string = [NSString stringWithFormat:@"%@api/v1/pokedex/1/", pokeApiBaseURL];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {


    self.pokemonArray = [responseObject objectForKey:@"pokemon"];
    self.pokemonDetailArray = [[responseObject objectForKey:@"pokemon"]valueForKey:@"resource_uri"];




   // NSLog(@"\n%@",detailString);

    [self.tableView reloadData];
    [self.refreshControl endRefreshing];


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"Request Failed: %@, %@", error, error.userInfo);

}];

[operation start];

这是我将其添加到单元格的位置

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdenifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdenifier forIndexPath:indexPath];


NSDictionary *pokemonDictionary = [self.pokemonArray objectAtIndex:indexPath.row];
NSDictionary *pokemonDetailDictionary = [self.pokemonDetailArray objectAtIndex:indexPath.row];


cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
[cell.textLabel sizeToFit];
cell.textLabel.text = [pokemonDictionary objectForKey:@"name"];
cell.detailTextLabel.text = @"PLACEHOLDER"; //WANT THE TYPE TO GO HERE!

return cell;

}

【问题讨论】:

    标签: arrays json dictionary afnetworking


    【解决方案1】:

    编辑

    今天早上我有一些空闲时间,因为一个客户没有回复我,并把它搞砸了:https://github.com/AlexTrott/PokeAPI:远非完美,这只是向您展示如何在第一次加载时在本地存储数据,如果您有任何问题请告诉我。



    这里是如何获取你想要的 URL 和信息(I used AFHTTPSessionManager as the method you use is about to be deprecated in AFN3):

    -(void)loadData {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:@"http://pokeapi.co/api/v1/pokedex/1/" parameters:nil success:^(NSURLSessionTask *task, id responseObject) {
            pokemonArray = [responseObject objectForKey:@"pokemon"];
            pokemonDetailArray = [[responseObject objectForKey:@"pokemon"]valueForKey:@"resource_uri"];
            [self loop];
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
    }
    
    -(void)loop {
        for (int i = 0; i < [pokemonArray count]; i++) {
            [self loadMore:i];
        }
    }
    
    -(void)loadMore:(int)pokemonID {
        NSString *url = [NSString stringWithFormat:@"%@%@", pokeApiBaseURL, [pokemonDetailArray objectAtIndex:pokemonID]];
        NSLog(@"URL = %@", url);
        NSLog(@"Loop Number = %d", pokemonID);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:url parameters:nil success:^(NSURLSessionTask *task, id responseObject) {
            NSLog(@"response = %@", responseObject);
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
    }
    

    我认为你需要重新考虑如何解决这个问题,我刚刚检查了 poke api,并且要执行你想要的操作,你必须进行 779 调用,1 是 pokedex 调用,另一个是 778 pokemon .

    您可以通过删除 pokedex 请求并仅根据数据形成一个数组来将其降低一个,但是您正在执行 778 请求,这在我看来很疯狂,我认为您需要弄清楚如何想要显示数据,如果您最好是第一次加载,或者自己编译数据并将其保存在本地,因为 778 请求太疯狂了。

    如果您确实需要执行这么多请求,请确保仅在他们第一次加载应用程序或其他内容时执行一次,然后将其存储在 CD 或领域或其他内容中。

    对于一个非常快速且肮脏的示例,将您的数据放入一个已排序的 NSMutableArray 中,请看一下这个,我不会这样做,我会在加载时对其进行批处理或本地存储,但它应该给出你更清楚自己想做什么。

    #import "ViewController.h"
    #import <AFNetworking/AFNetworking.h>
    
    @interface ViewController () {
        NSString *pokeApiBaseURL;
        NSMutableArray *pokedex;
    }
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable) name:@"orginalDone" object:nil];
        pokeApiBaseURL = @"http://pokeapi.co/";
        pokedex = [[NSMutableArray alloc] init];
        for (int i = 0; i < 151; i++) {
            [self loadData:i];
        }
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    
    -(void)loadData:(int)pokemonID {
        NSString *url = [NSString stringWithFormat:@"http://pokeapi.co/api/v1/pokemon/%d/", pokemonID];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:url parameters:nil success:^(NSURLSessionTask *task, id responseObject) {
            [self addPokemon:responseObject];
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
    }
    
    -(void)addPokemon:(id)pokemonObject {
        NSMutableDictionary *pokemonData = [[NSMutableDictionary alloc] init];
        [pokemonData setObject:pokemonObject[@"pkdx_id"] forKey:@"pkmnID"];
        [pokemonData setObject:pokemonObject[@"name"] forKey:@"pokemonName"];
        NSMutableArray *types = [[NSMutableArray alloc] init];
        for (int i = 0; i < [pokemonObject[@"types"] count]; i++) {
            [types addObject:pokemonObject[@"types"][i][@"name"]];
        }
        [pokemonData setObject:types forKey:@"types"];
        [pokedex addObject:pokemonData];
        NSLog(@"count = %lu", (unsigned long)[pokedex count]);
        if ([pokedex count] == 150) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"orginalDone" object:nil];
        }
    }
    
    -(void)updateTable {
        NSLog(@"Unsorted = %@", pokedex);
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"pkmnID" ascending:YES];
        [pokedex sortUsingDescriptors:[NSArray arrayWithObject:sort]];
        NSLog(@"Sorted = %@", pokedex);
    }
    
    @end
    

    【讨论】:

    • 哇,谢谢!我从未使用过 AFN,而且我的知识充其量是低于标准的。只是想在业余时间尝试一些东西。再次感谢您!
    • 没关系,我认为您只是选择了一个不好的示例 api 来使用,像公共 twitter 之类的东西会很棒,因为它有多个值和图像,所以处理数据是个好习惯
    • 我也试试推特!我将尝试使用您制作的 pokeapi 并使用情节提要,这样我就可以重新排列单元格中的标签。能够看到你的所有这些是如何处理的,这是一个巨大的帮助。
    【解决方案2】:

    我认为您可能正在寻找这种方法来将资源与基础结合起来:

    + (instancetype)URLWithString:(NSString *)URLString
                relativeToURL:(NSURL *)baseURL
    

    https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/clm/NSURL/URLWithString:relativeToURL:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2022-08-13
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多