[英]Download Images from url and store into Photo Gallery in Swift
从URL下载图像并显示在表格视图中,当我选择图像时,它将存储在照片库中。 我已经成功地从URL获取了图像并将其显示为表格视图,但是选择图像后无法将它们存储到Photo Gallery中。
这是我的代码:
var parsingdata = [Datavalues]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
let row = indexPath.row
let cellvalues = parsingdata[row] as Datavalues
cell.CategoryImage.downloadImageFrom(link: cellvalues.categoryImage, contentMode: .scaleToFill)
cell.categoryName.text = cellvalues.categoryName
cell.IDLabel.text = String(cellvalues.id)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow!
let imagestring = String(parsingdata[indexPath.row].categoryImage)
//Image add name is stored into the imagestring
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("Savedframe.png")
if !FileManager.default.fileExists(atPath: fileURL.path) {
do {
try UIImagePNGRepresentation(imagestring)!.write(to: fileURL)
print("Image Added Successfully")
} catch {
print(error)
}
} else {
print("Image Not Added")
}
}
我在哪里做错了? 我的目标是从url下载图像,选择图像后将其存储到Photo Gallery中。
尝试一下,在didSelectRowAt
方法中,将image
字符串转换为URL
并将其转换为Data
,将图像创建为Data
,将其保存如下。
如果您的图片尺寸过大,则需要在background thread
中将URL
转换为Data
并将image
保存到main thread
photosAlbum
。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let imagestring = String(parsingdata[indexPath.row].categoryImage)
if let url = URL(string: imagestring),
let data = try? Data(contentsOf: url),
let image = UIImage(data: data) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.