【问题标题】:Save UIImage in to core data or Image path after downloading with Asynchronously异步下载后将 UIImage 保存到核心数据或图像路径
【发布时间】:2016-01-02 01:55:15
【问题描述】:

我有一个获取数据的 api,包括来自 api 的图像 url 并将数据存储在 Core Data 中。

我正在使用 AFNetworking 异步获取数据,没有任何问题。

但是,我现在需要预取图像并将 UIImage 或其本地路径存储在 CoreData 中,而不是远程 url。

我对 AFHTTPSessionManager 进行了子类化并使用:

    return [self POST:urlPath parameters:parameters success:^(NSURLSessionDataTask * __unused task, id JSON) {

    NSArray *postsFromResponse = JSON;
    if([postsFromResponse count] > 0)
    {
        for (NSDictionary *resp in postsFromResponse)
        {

            gotResponse = YES;
            NSNumber *Id = [resp valueForKey:@"Id"];
            NSString  *imageUrl = [resp valueForKey:@"url"];

            Post*info = [self getPostWithId:Id];

                if (!info)
                {
                    info = (Post*)[NSEntityDescription insertNewObjectForEntityForName:@"Post" inManagedObjectContext:self.managedObjectContext];

                }
                info.imageUrl = imageUrl;

               .....
        }
}

我现在需要异步获取图像并将其存储在本地并将路径存储在实体中或将 UIImage 存储在实体中。除了在调用块之后获取正确实体对象的句柄之外,保存/存储不是问题。

我考虑过使用 AFNetworking + UIImage 并添加:

NSURL *url = [[NSURL alloc] initWithString:@"myUrl"]];
[info.image setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];

但是,如果我想在本地存储它,我需要使用回调方法 this 但我不知道如何获取正确的实体。

我想做:

__weak Post* weakPost = info;
[info.image setImageWithURLRequest:request placeholderImage:placeholderImage success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

 .... NSString *path = "....save UIIMage and get local path"
   weakPost.imagePath = path;

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
 }];

但当有多个帖子被迭代时,它不会将其存储在正确的实体中。

有没有人指引正确的方向?

【问题讨论】:

    标签: ios objective-c core-data uiimage afnetworking


    【解决方案1】:

    我的建议:不要在回调块中使用对现有实体对象的引用。相反,将实体的标识符传递给块。在块中,您可以根据标识符从本地数据库中检索实体对象,更新其图像 url 并保存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-31
      • 2023-03-14
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多