簡體   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