簡體   English   中英

從url下載圖像並存儲到Swift中的照片庫中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM