在 Swift 中解码图片在 Swift 中不起作用

Decoding pictures in Swift doesn't work in Swift

我这里有问题。我有一个包含图片的自定义对象数组。当我将我的应用程序安装到我的 phone 时,所有图片都在它们的位置,但是当我尝试使用 UserDefaults 将更改保存到我的数组时 - 除了图片之外,所有图片都在保存。我发现问题出在解码图片上。它们都更改为占位符图片。谁能帮我说说哪里错了?

 required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    englishWord = try container.decode(String.self, forKey: .englishWord)
    belarusianWord = try container.decodeIfPresent(String.self, forKey: .belarusianWord) ?? ""
    englishDefinition = try container.decodeIfPresent(String.self, forKey: .englishDefinition) ?? ""
    belarusianDefinition = try container.decodeIfPresent(String.self, forKey: .belarusianDefinition) ?? ""

    let data = try container.decodeIfPresent(Data.self, forKey: CodingKeys.wordImage)
    if let data = data {
        guard let wordImage = UIImage(data: data) else {
            throw NSError(domain: "Error decoding logo", code: 0, userInfo: nil)
        }
        self.wordImage = wordImage
    } else {
        wordImage = UIImage(named: "placeholder")!
    }
}

public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    let data = UIImage().pngData()
    try container.encode(data, forKey: CodingKeys.wordImage)
    try container.encode(self.englishWord, forKey: .englishWord)
    try container.encode(self.belarusianWord, forKey: .belarusianWord)
    try container.encode(self.englishDefinition, forKey: .englishDefinition)
    try container.encode(self.belarusianDefinition, forKey: .belarusianDefinition)
}

encode(to:)方法中,只需替换

let data = UIImage().pngData()

let data = self.wordImage.pngData()

在上面的人的回答后,我又遇到了一个问题。我的 UserDefaults 停止工作。

class FilesManager: NSObject {
static let shared = FilesManager()
private override init() {}

func saveData(data: Data, completion: (()->())?) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/words.dat"

    if !FileManager.default.fileExists(atPath: documentsPath) {
        FileManager.default.createFile(atPath: documentsPath,
                                       contents: nil,
                                       attributes: nil)
    } else {
        do {
            try FileManager.default.removeItem(atPath: documentsPath)
            FileManager.default.createFile(atPath: documentsPath,
                                           contents: nil,
                                           attributes: nil)
        } catch let error as NSError {
            print("File replacing failed: \(error)")
        }
    }

    let file: FileHandle? = FileHandle(forWritingAtPath: documentsPath)
    if file != nil {
        file?.write(data)
        file?.closeFile()
        print("Data saved to file")
        if let completion = completion {
            completion()
        }
    } else {
        print("Ooops! Something went wrong!")
    }
}

func loadData() -> Data? {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/words.dat"

    let file: FileHandle? = FileHandle(forReadingAtPath: documentsPath)
    if file != nil {
        let data = file?.readDataToEndOfFile()
        file?.closeFile()
        print("Data loaded from file")
        return data
    }
    else {
        print("Ooops! Something went wrong!")
        return nil
    }
}

}

如果let data = UIImage().pngData()留下来,一切正常!