简体   繁体   中英

Download Images from url and store into Photo Gallery in Swift

Downloading images from the URL and showing into the table view, when I select the image it will store into the Photo Gallery. I have successfully got images from urls and showing to table view but am not able to store them into Photo Gallery after the selection of the image.

This is my code:

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")
    }
}

Where did I do wrong? My aim is download image from url, store them into Photo Gallery when image is selected.

Try this, in didSelectRowAt method, Convert your image string to URL and convert it into Data , Once Image is created as Data than save it like below.

If your images are of large size than you need to convert URL to Data in background thread and save image to photosAlbum in main thread .

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM