在设备中查找路径时出错

时间:2016-02-03 13:17:55

标签: ios swift

我只是将Data.csv文件拖到导航器面板中的应用程序文件夹中,我正在尝试将文件的正确路径设置到应用程序中。

下面的代码我用于模拟器并且工作正常,但是为了在设备中运行我改为第二块代码,然后我得到了这个错误:

数据[399:157757] CFURLCopyResourcePropertyForKey失败,因为它传递了一个没有方案的URL
错误域= NSCocoaErrorDomain代码= 256"无法打开文件“Documents”。"
的UserInfo = {NSURL =的/ var /移动/容器/数据/应用/ C7756542-6922-4C6F-A98E-C6F407B2063E /文档}

//code to show the path in the simulator:
         guard let remoteURL = NSURL(string: "/Users/mbp/Library/Developer/CoreSimulator/Devices/7F25FC7C-F2B2-464E-85B4-A2B96DB83F17/data/Containers/Bundle/Application/F285940D-7776-4EE2-83A1-D54DD3411E0E/Data.app/Data.csv") else {
            return
        }

阻止在设备中运行应用程序:

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


        let sourcePath = NSBundle.mainBundle().pathForResource(“Data”, ofType: "csv")
        print(sourcePath)

        let filename = "Data.csv"
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        let destinationPath = documentsPath + "/" + filename

        do {
            try NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath)
        } catch _ {
        }

Try to load the file
        let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "DataEntity")
        fetchRequest.fetchLimit = 1
        do {
            let result = try managedObjectContext.executeFetchRequest(fetchRequest)
            if result.count == 0 {
                 preloadData()
            }
        } catch let error as NSError {
            print("Error: \(error.domain)")
        }


    func preloadData () {

        guard let remoteURL = NSURL(string:NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) else {
            return
        }
        }

1 个答案:

答案 0 :(得分:6)

通过NSURL处理文件路径可以避免设备和模拟器之间的不匹配。


        let srcURL = NSBundle.mainBundle().URLForResource("Data", withExtension: "csv")!
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        var toURL = NSURL(string: "file://\(documentsPath)")!
        toURL = toURL.URLByAppendingPathComponent(srcURL.lastPathComponent!)
        do {
            try NSFileManager().copyItemAtURL(srcURL, toURL: toURL)
            self.preloadData(toURL)
        } catch let error as NSError {
            print(error.localizedDescription)
        }

        func preloadData(toURL: NSURL) {
            print("=== Success and print toURL ===")
            print(toURL)
        }