iOS - Swift 我如何知道 copyItemAtPath 何时完成?

Posted

技术标签:

【中文标题】iOS - Swift 我如何知道 copyItemAtPath 何时完成?【英文标题】:iOS - Swift How do i know when copyItemAtPath has been finished? 【发布时间】:2016-06-08 11:36:46 【问题描述】:

我想在开始时创建预种子数据库 该文件非常大(5mb)。

我用copyItemAtPath复制文件,请问这个方法有完成吗? 我怎么知道这个过程何时完成?

【问题讨论】:

copyItemAtPath 方法返回时复制完成,它不是异步的。否则它如何通过抛出错误来报告失败? 【参考方案1】:

这段代码就够了:

do 
    // copy files from main bundle to documents directory
    print("copy")
    try 
        NSFileManager.defaultManager().copyItemAtPath(sourcePath, toPath: destinationPath)
 catch let error as NSError 
     // Catch fires here, with an NSError being thrown
     print("error occurred, here are the details:\n \(error)")

destinationPath 可以是例如:

NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).first

【讨论】:

【参考方案2】:

来自How to show the progress of copying a large file in ios?

    在单独的线程 (T1) 中运行复制过程 运行另一个定期读取的线程 (T2)(比如每 100 毫秒) 目标文件 current_size。 计算百分比以显示进度:current_size / total_size

【讨论】:

以上是关于iOS - Swift 我如何知道 copyItemAtPath 何时完成?的主要内容,如果未能解决你的问题,请参考以下文章