【发布时间】: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