在设备中查找路径时出错

Man*_*olo 1 ios swift

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

下面我用模拟器和完美的作品,但在我改变代码的第二块设备上运行的代码,然后我得到这个错误:

数据[399:157757] CFURLCopyResourcePropertyForKey失败,因为它是通过它没有一个URL scheme
错误Domain = NSCocoaErrorDomain Code = 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
        }
Run Code Online (Sandbox Code Playgroud)

阻止在设备中运行应用:

  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
        }
        }
Run Code Online (Sandbox Code Playgroud)

All*_*len 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)
        }
Run Code Online (Sandbox Code Playgroud)