SetUbiquitous show'文件已经存在'对于没有的文件

时间:2016-10-07 18:20:27

标签: ios swift icloud appdelegate

AppDelegate.swift中,首次启动时,目的是将一些示例文档放在本地Documents文件夹中,或者如果启用了iCloud,则放在iCloud Documents文件夹中。

    var templates = NSBundle.mainBundle().pathsForResourcesOfType(AppDelegate.myExtension, inDirectory: "Templates")
    dispatch_async(appDelegateQueue) {
        self.ubiquityURL = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)
        if self.ubiquityURL != nil && templates.count != 0 {
            // Move sample documents from Templates to iCloud directory on initial launch
            for template in templates {
                let tempurl = NSURL(fileURLWithPath: template)
                let title = tempurl.URLByDeletingPathExtension?.lastPathComponent

                    let ubiquitousDestinationURL = self.ubiquityURL?.URLByAppendingPathComponent(title!).URLByAppendingPathExtension(AppDelegate.myExtension)
                    // let exists = NSFileManager().isUbiquitousItemAtURL(ubiquitousDestinationURL!)
                    do {
                        try NSFileManager.defaultManager().setUbiquitous(true, itemAtURL: tempurl, destinationURL: ubiquitousDestinationURL!)
                    }
                    catch let error as NSError {
                        print("Failed to move file \(title!) to iCloud: \(error)")
                    }
            }
        }
        return
    }

在运行此功能之前,我会从设备中删除该应用,并确保iCloud中没有该名称的文档。首次启动时,如果没有iCloud,示例文档将正确复制到本地Documents文件夹中。使用iCloud时,此代码会运行,setUbiquitous调用会导致错误,表明该文件已存在。对isUbiquitousItemAtURL的评论调用也会返回true。

可能会使这些调用注册一个文件存在,我很确定不会?谢谢!

2 个答案:

答案 0 :(得分:0)

该文件已存在,因此只需将其替换

即可

答案 1 :(得分:0)

主要解决方案......在所有试验和错误中,我忘记将“文档”放回到网址中。应该是:

let ubiquitousDestinationURL = self.ubiquityURL?.URLByAppendingPathComponent("Documents").URLByAppendingPathComponent(title!).URLByAppendingPathExtension(AppDelegate.myExtension)

没有它,将文件写入错误的目录,因此我无法通过正常方式看到它。