[英]Save UIImage in to core data or Image path after downloading with Asynchronously
I have an api which gets data, including an Image url from an api and store the data in Core Data. 我有一个api,它获取数据,包括来自api的图片网址,并将数据存储在Core Data中。
I am using AFNetworking to get the data asynchronously with no issues. 我正在使用AFNetworking毫无问题地异步获取数据。
However, I now need to prefetch the image and store the UIImage or its local path in CoreData instead of the remote url. 但是,我现在需要预取图像并将UIImage或其本地路径存储在CoreData中,而不是远程URL中。
I have subclassessed AFHTTPSessionManager and use: 我对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;
.....
}
}
I now need to asynchronously get the image and either store it locally and store the path in the Entity or store the UIImage in the Entity. 现在,我需要异步获取图像并将其存储在本地并将路径存储在Entity中或将UIImage存储在Entity中。 The saving/storing is not an issue apart from getting a handle to the Correct Entity object after the call block.
除了在调用块之后获取正确实体对象的句柄之外,保存/存储不是问题。
I thought about using AFNetworking + UIImage and adding: 我考虑过使用AFNetworking + UIImage并添加:
NSURL *url = [[NSURL alloc] initWithString:@"myUrl"]];
[info.image setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
However, if I want to store it locally, I need to use the call back method this but I don't know how to get the correct Entity. 但是,如果要将其存储在本地,则需要使用回调方法this,但我不知道如何获取正确的Entity。
I want to do: 我想要做:
__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) {
}];
But it is not storing it in the correct Entity when there are multiple posts being iterated through. 但是,当有多个帖子正在迭代时,它不会将其存储在正确的Entity中。
Does anyone have a steer in the right direction? 有人指导方向正确吗?
My suggestion: don't use a reference to the existing entity object inside your callback block. 我的建议:不要在回调块中使用对现有实体对象的引用。 Instead, pass an identifier of the entity to the block.
而是将实体的标识符传递给该块。 Inside the block you retrieve the entity object from your local database, based on the identifier, update its image url and save it.
在该块内,您根据标识符从本地数据库中检索实体对象,更新其图像URL并保存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.