【问题标题】:How to cache the images offline in swift(without internet connection)?如何快速离线缓存图像(没有互联网连接)?
【发布时间】:2018-09-17 13:06:52
【问题描述】:

当用户有互联网连接时,我能够获取图像并缓存它。但是如何离线缓存图像(当用户没有互联网连接时,尝试打开应用程序)。下面是我的代码

func downloadImages(){
        let storage = Storage.storage().reference()



        for i in animated_images{
            let storageRef = storage.child("images/\(i).jpg")
            storageRef.downloadURL { (url, error) in
                if let error = error{
                    print(error.localizedDescription)
                }
                else{
                    self.downloaded_images.updateValue(url!, forKey: i)
                    self.tableView.reloadData()
                }
            }
        }

    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! demoCell
        cell.textDemo.text = images[indexPath.row]

        var image1 = downloaded_images[images[indexPath.row]]
        var image2 = downloaded_images[images[indexPath.row]+"1"]

        var value1 = SDImageCache.shared().imageFromCache(forKey: image1?.absoluteString)
        var value2 = SDImageCache.shared().imageFromCache(forKey: image2?.absoluteString)

        if let downloadURL1 = value1, let downloadURL2 = value2{
            cell.imageDemo.animationImages = [downloadURL1,downloadURL2]
            cell.imageDemo.animationDuration = 2
            cell.imageDemo.startAnimating()
        }
        else{
            cell.imageDemo.sd_setAnimationImages(with: [image1!,image2!])
            cell.imageDemo.animationDuration = 2
            cell.imageDemo.startAnimating()
        }

        return cell
    }

我是 iOS 开发新手,我对 Coredata 和 sqlite 有一些想法。请指导我如何在没有互联网连接的情况下进行操作。提前致谢

【问题讨论】:

  • 首先,您似乎没有使用 Core Data。所以你首先需要决定你是否使用Core Data。这就是 Xcode 在 File > New Project 期间询问您的原因。如果你确实想使用Core Data,你会重写上面的部分代码,如何离线缓存图片可以在各种问题中找到答案,例如this one

标签: swift firebase cocoa-touch core-data firebase-storage


【解决方案1】:

为了在没有 Internet 连接的情况下在我的应用程序中显示图像,我创建了一个名为 cached_image 的表,其中包含字段 image_name 和 download_url 并保存了图像的相应 url。当应用程序被加载时,那些从本地 sqlite db 获取的 cached_images 详细信息并显示图像

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多