如何使用Swift关闭打开的文件?

时间:2017-11-21 17:46:31

标签: ios swift compiler-errors storing-data xcode9.1

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

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

很明显,下载的png图像没有关闭。

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

if(/=(.*)$/) {            # Grab everything after the = into $1
    my $rest = $1;        # copy $1 to writeable variable $rest
    $rest =~ s/UTC\s+//;  # Remove "UTC" and any following whitespace from $rest
    print $rest;          # Output to the console (you could do something else instead)
}

这是我存储图像的方法:

    // 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

将所有这些内容添加到userDefault后,我收到错误。所以,我知道他们在那里。

编辑:

功能

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

用法:

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

1 个答案:

答案 0 :(得分:1)

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

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

您提到您在UserDefaults中保存了1300张图片。这不是存储该类型数据的正确位置,也不是存储该数量的文件的正确位置。我建议你使用File System Programming Guide: The Library Directory Stores App-Specific Files中概述的“Caches”文件夹。

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)

不要试图将它们存储在“Documents”文件夹中。有关详细信息,请参阅iOS Storage Best Practices