【问题标题】:how can I use Api for downloading pictures in all of the view controllers in page view controller?如何使用 Api 在页面视图控制器中的所有视图控制器中下载图片?
【发布时间】:2017-07-20 18:45:18
【问题描述】:

我的应用程序中有一个页面视图控制器,这个页面视图控制器有 4 个视图控制器 - 所以我在所有这些页面视图控制器中都有图像视图,我想使用 Json Api 下载这些页面中的图像

这是我的代码,但我在所有视图控制器类中都复制了这段代码,所以我只在这里写一个

func refreshingphoto1() {

    let firstImageURL = URL(string: "http://img.autobytel.com/car-reviews/autobytel/11694-good-looking-sports-cars/2016-Ford-Mustang-GT-burnout-red-tire-smoke.jpg")!

    let session = URLSession(configuration: .default)

    // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.


    let downloadPicTask = session.dataTask(with: firstImageURL) { (data, response, error) in
        // The download has finished.

        if error != nil {
            print("Error downloading picture")
            self.firstImageJson.image = UIImage(named: "1.jpg")
        } else {

            // No errors found.
            // It would be weird if we didn't have a response, so check for that too.
            if (response as? HTTPURLResponse) != nil {

                print("Downloaded picture with response code")

                if let imageData = data {

                    // Finally convert that Data into an image and do what you wish with it.
                    let image = UIImage(data: imageData)
                    self.firstImageJson.image = image
                    // Do something with your image.

                } else {


                    print("Couldn't get image: Image is nil")
                    self.firstImageJson.image = UIImage(named: "1.jpg")

                }
            } else {
                print("Couldn't get response code for some reason")
                self.firstImageJson.image = UIImage(named: "1.jpg")
            }
        }
    }
    downloadPicTask.resume()
}
}

**这可行,但不完全正确**

这是我的故事板的图片

as you see in the picture I have Page VC2 that is page view controller and four view controllers that connected to the page VC2

【问题讨论】:

    标签: ios json api swift3 uipageviewcontroller


    【解决方案1】:

    您拥有多个 VC 的事实与下载图像的任务无关。

    但是,除了缺乏抽象之外,您的做法是正确的:使用 URLSessionURLSessionTask 是使用 Apple API 的正确方法。

    不过,您可能对以下内容感兴趣;为了抽象事物,很多开发人员使用这个名为 Alamofire 的第三方库,专门针对您的情况 AlamofireImage

    例如使用 AlamofireImage 你只需要这样做

    let imageView = UIImageView(frame: frame)
    let url = URL(string: "https://httpbin.org/image/png")!
    let placeholderImage = UIImage(named: "placeholder")!
    
    imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)
    

    【讨论】:

    • 它在寻找字典吗?还是不行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2012-12-02
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多