Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / ios / chrome / browser / suggestions / image_fetcher_impl.mm
blob01cde4860735bd92bd2c8fcf7f8a9be9a4950887
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ios/chrome/browser/suggestions/image_fetcher_impl.h"
7 #include <UIKit/UIKit.h>
9 #include "base/threading/sequenced_worker_pool.h"
10 #include "ios/chrome/browser/net/image_fetcher.h"
11 #include "net/url_request/url_request_context_getter.h"
12 #include "skia/ext/skia_utils_ios.h"
14 namespace suggestions {
16 ImageFetcherImpl::ImageFetcherImpl(
17     net::URLRequestContextGetter* url_request_context,
18     base::SequencedWorkerPool* blocking_pool) {
19   imageFetcher_.reset(new image_fetcher::ImageFetcher(blocking_pool));
20   imageFetcher_->SetRequestContextGetter(url_request_context);
23 ImageFetcherImpl::~ImageFetcherImpl() {
26 void ImageFetcherImpl::SetImageFetcherDelegate(ImageFetcherDelegate* delegate) {
27   DCHECK(delegate);
28   delegate_ = delegate;
31 void ImageFetcherImpl::StartOrQueueNetworkRequest(
32     const GURL& url,
33     const GURL& image_url,
34     base::Callback<void(const GURL&, const SkBitmap*)> callback) {
35   if (image_url.is_empty()) {
36     callback.Run(url, nullptr);
37     if (delegate_) {
38       delegate_->OnImageFetched(url, nullptr);
39     }
40     return;
41   }
42   // Copy url reference so it's retained.
43   const GURL page_url(url);
44   image_fetcher::ImageFetchedCallback fetcher_callback =
45       ^(const GURL& original_url, int response_code, NSData* data) {
46       if (data) {
47         // Most likely always returns 1x images.
48         UIImage* image = [UIImage imageWithData:data scale:1];
49         if (image) {
50           SkBitmap bitmap =
51               gfx::CGImageToSkBitmap(image.CGImage, [image size], YES);
52           callback.Run(page_url, &bitmap);
53           if (delegate_) {
54             delegate_->OnImageFetched(page_url, &bitmap);
55           }
56           return;
57         }
58       }
59       callback.Run(page_url, nullptr);
60       if (delegate_) {
61         delegate_->OnImageFetched(page_url, nullptr);
62       }
63   };
64   imageFetcher_->StartDownload(image_url, fetcher_callback);
67 }  // namespace suggestions