当前位置: 动力学知识库 > 问答 > 编程问答 >

osx - Swift - When a user selects a file, it says that path doesn't exist

问题描述:

In my program, the user can select a file, then that is opened up in an app of their choosing. The problem I'm running into is that originally the app opened up, but without (running) the file. It turned out that I had an issue with the variable not being global so it was blank. Now I fixed that issue, and the app doesn't open at all.

So first the User selects a file, then selects what app to open it with.

For example the path that I am getting from the test file I am using is: file:///Users/Panja/Documents/test.txt

Then I run that through NSFileManager.defaultManager().fileExistsAtPath(filePath) and it comes back false

So when I try to open the app, it doesn't open because the NSWorkspace.sharedWorkspace().openFile(filePath, withApplication "TextEdit"); comes back false so an error occurred. I then did NSWorkspace.sharedWorkspace().openFile(filePath) to prove that the withApplication wasn't causing the problem.

I have an extension I got from another SO answer, to get the filePath so that will be below also:

Select_File.swift (Extension):

import Foundation

import Cocoa

extension NSOpenPanel {

var selectUrl: NSURL? {

title = "Select File"

allowsMultipleSelection = false

canChooseDirectories = false

canChooseFiles = true

canCreateDirectories = false

allowedFileTypes = ["txt"];

runModal()

return URLs.first

}

}

AppDelegate.swift

- Only the important parts

@IBAction func browseForTextFile(sender: AnyObject) {

if let textPath = NSOpenPanel().selectUrl{

print("Path Grabbed");

do {

tP = String(textPath);

let controller = NSWindowController(window: appSelection)

controller.showWindow(self)

}catch let error as NSError {

print(error.localizedDescription)

}

}else{

print("The user clicked the cancel button");

}

}

@IBAction func openFileWithTextEdit(sender: AnyObject) {

print(tP);

var openWithTE = NSWorkspace.sharedWorkspace().openFile(tP, withApplication: "Text Edit");

print(NSFileManager.defaultManager().fileExistsAtPath(tP));

if(openWithTE == true){

print("Should have opened correctly");

}else{

print("Error detected, file not opening correctly");

}

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: