繁体   English   中英

异步下载后将UIImage保存到核心数据或图像路径中

[英]Save UIImage in to core data or Image path after downloading with Asynchronously

我有一个api,它获取数据,包括来自api的图片网址,并将数据存储在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;

               .....
        }
}

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

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

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

但是,如果要将其存储在本地,则需要使用回调方法this,但我不知道如何获取正确的Entity。

我想要做:

__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) {
 }];

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

有人指导方向正确吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM