3

我正在下载约 1300 张图片。这些是小图像,总大小约为 500KB。但是,在下载并将它们放入 userDefault 后,我​​收到如下错误:

libsystem_network.dylib: nw_route_get_ifindex :: socket(PF_ROUTE, SOCK_RAW, PF_ROUTE) 失败:[24] 打开的文件太多

假设,下载的 png 图像没有被关闭。

我已经通过以下方式扩展了缓存大小:

    // Configuring max network request cache size
    let memoryCapacity = 30 * 1024 * 1024 // 30MB
    let diskCapacity = 30 * 1024 * 1024   // 30MB
    let urlCache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "myDiscPath")
    URLCache.shared = urlCache

这是我存储图像的方法:

    func storeImages (){
        for i in stride(from: 0, to: Cur.count, by: 1) {
            // Saving into userDefault
            saveIconsToDefault(row: i)
        }
    }

在将所有这些都添加到 userDefault 中后,我得到了错误。所以,我知道他们在那里。

编辑:

功能:

func getImageFromWeb(_ urlString: String, closure: @escaping (UIImage?) -> ()) {
    guard let url = URL(string: urlString) else {
        return closure(nil)
    }
    let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
        guard error == nil else {
            print("error: \(String(describing: error))")
            return closure(nil)
        }
        guard response != nil else {
            print("no response")
            return closure(nil)
        }
        guard data != nil else {
            print("no data")
            return closure(nil)
        }
        DispatchQueue.main.async {
            closure(UIImage(data: data!))
        }
    }; task.resume()
}

func getIcon (id: String, completion: @escaping (UIImage) -> Void) {
    var icon = UIImage()

    let imageUrl = "https://files/static/img/\(id).png"

        getImageFromWeb(imageUrl) { (image) in
            if verifyUrl(urlString: imageUrl) == true {
                if let image = image {
                    icon = image
                    completion(icon)
                }
            } else {
                if let image = UIImage(named: "no_image_icon") {
                    icon = image
                    completion(icon)
                }
            }
        }
}

用法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CurrencyCell", for: indexPath) as? CurrencyCell else { return UITableViewCell() }

    if currencies.count > 0 {
        let noVal = currencies[indexPath.row].rank ?? "N/A"
        let nameVal = currencies[indexPath.row].name ?? "N/A"
        let priceVal = currencies[indexPath.row].price_usd ?? "N/A"

        getIcon(id: currencies[indexPath.row].id!, completion: { (retImg) in
            cell.configureCell(no: noVal, name: nameVal, price: priceVal, img: retImg)
        })
    }
    return cell
}
4

1 回答 1

1

语法是为每个请求URLSession(configuration: .default)创建一个新的。URLSession创建一个URLSession(将其保存在某个属性中),然后将其重用于所有请求。或者,如果您真的没有对 进行任何自定义配置URLSession,只需使用URLSession.shared

let task = URLSession.shared.dataTask(with: url) { data, response, error in
    ...
}
task.resume()

您提到您将 1300 张图像保存在UserDefaults. 那不是存储该类型数据或该数量文件的正确位置。我建议您使用文件系统编程指南中概述的“缓存”文件夹:库目录存储应用程序特定文件

let cacheURL = try! FileManager.default
    .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("images")

// create your subdirectory before you try to save files into it
try? FileManager.default.createDirectory(at: cacheURL, withIntermediateDirectories: true)

也不要试图将它们存储在“文档”文件夹中。有关更多信息,请参阅iOS 存储最佳实践

于 2018-01-10T18:29:26.537 回答