代码之家  ›  专栏  ›  技术社区  ›  user8797533

从url下载图像并存储到Swift中的照片库中

  •  2
  • user8797533  · 技术社区  · 8 年前

    从URL下载图像并显示到表视图中,当我选择图像时,它将存储到照片库中。我已成功从URL获取图像并显示到表视图,但在选择图像后无法将其存储到照片库中。

    这是我的代码:

    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下载图像,选择图像后将其存储到照片库中。

    1 回复  |  直到 7 年前
        1
  •  9
  •   Cœur Gustavo Armenta    7 年前

    试试这个,在 didSelectRowAt 方法,转换 image 字符串到 URL 并将其转换为 Data ,一旦图像创建为 数据 而不是像下面这样保存它。

    如果您的图像比需要转换的图像大 URL地址 数据 在里面 background thread 并保存 形象 photosAlbum 在里面 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)
        }
    }