Downloading UIImage via AlamofireImage? [duplicate]

雨燕双飞 提交于 2019-11-26 11:37:24

问题


I have a URL and want to download the image via a return function, however I cant get it to cooperate properly, here is my func:

func getTabImage(url: URL) -> UIImage {
    Alamofire.request(url)
        .responseImage { response in
            if let image = response.result.value {
                return image
            } else {
                print(\"Failed to get image\")
            }
    }
}

I pass in the URL, and want a UIImage returned from the alamofire response.

But i get

Unexpected non-void return value in void function

for the return statement.

How can i achieve this correctly?


回答1:


You can use the below function for downloading the image:

func getImage(_ url:String,handler: @escaping (UIImage?)->Void) {
        print(url)
        Alamofire.request(url, method: .get).responseImage { response in
            if let data = response.result.value {
                handler(data)
            } else {
                handler(nil)
            }
        }
    }

Uses

getImage("http://") { (image) in
    if image != nil {
        print(image)
    }
}

Or

If you want to set the image on UIImageView use extension of AlamofireImage.

if let imageURL = URL(string: "http://"), let placeholder = UIImage(named: "default") {
     imageView.af_setImage(withURL: imageURL, placeholderImage: placeholder) //set image automatically when download compelete.
}


来源:https://stackoverflow.com/questions/46199203/downloading-uiimage-via-alamofireimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!