是否应该在警报“背后”进行处理?

时间:2019-02-26 19:21:19

标签: swift uialertcontroller

我正在编写一个例程来检查文件是否存在,如果存在,则警告用户并询问是否应覆盖。我对我来说是奇怪的行为。

这是我编写文件的代码。

    if let jsonToSave = myFile.json {
            var shouldIOverwrite: Bool = false
          if let url = try? FileManager.default.url(
                for: .documentDirectory,
                in: .userDomainMask,
                appropriateFor: nil,
                create: true
                ).appendingPathComponent(name + ".json"){
                do {
                    print("place 1: \(shouldIOverwrite)")
                     shouldIOverwrite = presentOverwriteWarning(for: url, fName: name)
                    print("place 2: \(shouldIOverwrite)")
                    if shouldIOverwrite {   
                        try jsonToSave.write(to: url)
                        print("saved successfully")
                    }
                } catch let error {
                    print("couldn't save \(error)")
                }
            }
        }

这是设置和显示警报的功能:

private func presentOverwriteWarning(for url: URL?, fName: String) -> Bool {
    var overwrite: Bool = false

        let alert = UIAlertController(
            title: "File for \"" + fName + "\" exists",
            message: "Do you want to overwrite it?",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(
            title: "Yes",
            style: .default,
            handler: { action in
                 overwrite = true
        }
        ))
        alert.addAction(UIAlertAction(
            title: "No",
            style: .default,
            handler: { action in
                overwrite = false
        }
        ))
        present(alert, animated: true)

    return overwrite
}

我正在返回布尔值覆盖。注意,我有两个打印命令“ place 1”和“ place 2”。我调试时看到的是,在警报响起之前,在我的屏幕上显示之前,输出中已经列出2张打印品,它们为false。所以我的“如果覆盖”总是错误的。我是否在警报中缺少某些东西?

注意:您将看到没有代码可检查文件是否存在。对于调试,我总是调用警报。

1 个答案:

答案 0 :(得分:1)

由于警报是异步的,因此我将您的presentOverwriteWarning函数更改为使用回调,而不是使其返回任何内容:

private func presentOverwriteWarning(for url: URL?, fName: String, callback: (Bool) -> Void) {
    let alert = UIAlertController(
        title: "File for \"" + fName + "\" exists",
        message: "Do you want to overwrite it?",
        preferredStyle: .alert
    )
    alert.addAction(UIAlertAction(
        title: "Yes",
        style: .default,
        handler: { action in
            callback(true)
    }
    ))
    alert.addAction(UIAlertAction(
        title: "No",
        style: .default,
        handler: { action in
            callback(false)
    }
    ))
    present(alert, animated: true)
}

然后您可以像这样使用它:

presentOverwriteWarning(for: url, fName: name) { overwrite in
    if (overwrite) {
         try jsonToSave.write(to: url)
    }
}

更新:要修复与try jsonToSave相关的编译错误,您需要移动do-catch块:

presentOverwriteWarning(for: url, fName: name) { overwrite in
    if (overwrite) {
         do {
            try jsonToSave.write(to: url)
         } catch {

         }
    }
}