无法将已保存的JSON数据加载到View中

问题描述 投票:0回答:1

在我创建的基于文档的应用程序中,我有一个名为“TestDraw”的视图,我可以从collectionView中拖放UILables。在“TestDraw”上,也允许自由绘图......

我还设置了BarItems来保存用户放置UILabel的位置及其上的信息,以便以后可以将该信息解码到卡对象中...

但是,每次打开我认为已成功保存的JSON文件时,结果都是空白的......

我试图将保存文件的jsonString打印到控制台,证明是正确的,因此显示信息已成功保存。

这是NumberCardsSetDocument中的代码:

class NumberCardsSetDocument: UIDocument {

var numberCardsSet: NumberCardsSet?

override func contents(forType typeName: String) throws -> Any {
    // Encode your document with an instance of NSData or NSFileWrapper
    return numberCardsSet?.json ?? Data()
}

override func load(fromContents contents: Any, ofType typeName: String?) throws {
    if let json = contents as? Data{
        numberCardsSet = NumberCardsSet(json: json)
    }else {
        print("Error trying to load NumberCards. Content is not JSON data")
    }
  }
}

这是NumberCardsSet中的代码:

struct NumberCardsSet: Codable{
var numberCards = [CardInfo]()
struct CardInfo: Codable{
    let x: Int
    let y: Int
    let text: String
    let size: Int
}
init?(json:Data){
    if let newValue = try? JSONDecoder().decode(NumberCardsSet.self, from: json){
        self = newValue
    }else{
        return nil
    }
}
var json: Data? {
    return try? JSONEncoder().encode(self)
}
init (numberCards:[CardInfo]){
    self.numberCards = numberCards
}
}

这就是我想要加载保存的数据:

class DocumentBrowserViewController: UIDocumentBrowserViewController, UIDocumentBrowserViewControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    delegate = self
    allowsPickingMultipleItems = false
    allowsDocumentCreation = true
    template = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("UntitledHMS.json")
    if template != nil {
        allowsDocumentCreation = FileManager.default.createFile(atPath: template!.path, contents: Data() )
    }
}

var template:URL?
// MARK: UIDocumentBrowserViewControllerDelegate

func documentBrowser(_ controller: UIDocumentBrowserViewController, didRequestDocumentCreationWithHandler importHandler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {
    importHandler(template,.copy)
}

func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) {
    guard let sourceURL = documentURLs.first else { return }
    presentDocument(at: sourceURL)
}

func documentBrowser(_ controller: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL, toDestinationURL destinationURL: URL) {
    presentDocument(at: destinationURL)
}

func documentBrowser(_ controller: UIDocumentBrowserViewController, failedToImportDocumentAt documentURL: URL, error: Error?) {
}

// MARK: Document Presentation
func presentDocument(at documentURL: URL) {
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let documentVC = storyBoard.instantiateViewController(withIdentifier: "DocumentMVC")
    if let trailMakingTestViewController = documentVC.contents as? DocumentViewController{
        trailMakingTestViewController.document = NumberCardsSetDocument(fileURL: documentURL)
    }
    present(documentVC,animated: true)
}
}

我认为问题可能在于解码信息的过程。希望有人能给我一些线索。这是我第一次尝试自己构建一个复杂的应用程序。

ios json swift encoding decoding
1个回答
1
投票

我想你可以进一步缩小范围。你有这条线

return try? JSONEncoder().encode(self)

并且你在代码中处理nil返回,这没关系。

但如果您怀疑您的编码可能失败,获得更好信息的一种方法是在do - catch周围使用适当的try块而不是使用try?。如果您只是将错误打印到控制台,它可能会有所帮助。根据我的经验,这些消息有助于指出无法编码(或解码)的原因。

© www.soinside.com 2019 - 2024. All rights reserved.