swift - Converting Array of URLs into Array of UIImage -
i have array of urls linking image files, how store them array of uiimages?
var imagesarray = [uiimage]() let links = ["http://example.com/image1.jpg","http://example.com/image2.jpg"] [string] there must easy solution. if 1 image following:
let url = url(string: link2image!)! let imagedata = try? data(contentsof: url) let image = uiimage(data: imagedata!)! self.image.append(image)
the easiest solution iterate through array , download images synchronously using data(contentsof:), however, quite insufficient due synchronous execution.
let images = links.flatmap{ link->uiimage? in guard let url = url(string: link) else {return nil} guard let imagedata = try? data(contentsof: url) else {return nil} return uiimage(data: imagedata) } a better solution download images asynchronously in parallel, have written uiimage extension using promisekit:
extension uiimage { class func downloadedasync(fromurl url: url)->promise<uiimage> { return promise{ fulfill, reject in urlsession.shared.datatask(with: url, completionhandler: { data, response, error in guard let data = data, error == nil else { reject(error!); return } guard let httpresponse = response as? httpurlresponse, httpresponse.statuscode == 200 else { reject(nserror(domain: "wrong http response code when downloading image asynchronously",code: (response as? httpurlresponse)?.statuscode ?? 1000));return } guard let mimetype = response?.mimetype, mimetype.hasprefix("image"), let image = uiimage(data: data) else { reject(nserror(domain: "no image in response", code: 700)); return } fulfill(image) }).resume() } } } you call array of links this:
var imagedownloadtasks = links.flatmap{ link in guard let url = url(string: link) else {return nil} return uiimage.downloadedasync(fromurl: url) } then execute promises:
when(fulfilled: imagedownloadtasks).then{ images in //use images, images of type [uiimage] }
Comments
Post a Comment