copy from main bundle to application support swift - macos

I have copied files like this from an application before and have copied the code exactly as it appears in another app but for what ever reason when it try to run this particular code it will only create the new directory.
It will not however save the binary file I have saved in supporting files in the main bundle to the new directory. I have done a fair amount of googling and searching stack overflow and have decided I might have to post something here.
let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("youtube-dl")
let destination = "~/Library/Application Support/Youtube DLX/"
let destinationPath = destination.stringByStandardizingPath
NSFileManager.defaultManager().createDirectoryAtPath(destinationPath, withIntermediateDirectories: true, attributes: nil, error: nil)
NSFileManager.defaultManager().copyItemAtPath(path!, toPath: destinationPath + "youtube-dl", error: nil)
note that the file that I am trying to copy has no extension so the full name is just "youtube-dl"

The result of
let destinationPath = destination.stringByStandardizingPath
has no trailing slash, so you are trying to copy the file to
"~/Library/Application Support/Youtube DLXyoutube-dl"
You should use
destinationPath.stringByAppendingPathComponent("youtube-dl")
to generate the target path as you already did for the source path.
Generally (as just mentioned in a comment), you should use the error parameter and
check the return value for success, for example
var error : NSError?
if !NSFileManager.defaultManager().copyItemAtPath(..., error: &error) {
println("copy failed: \(error)")
}

Related

To check whether a file has been downloaded or not via protractor

Need help to check whether a file has been successfully downloaded or not in a specified folder.
The file name dynamically changes every time a new file is downloaded but the initial part of the file "Pivot_Report" always stays the same
The actual file gets downloaded in the mentioned folder but protractor is not able to find it with just the initial part of the full name
This is the code I'm using (filenamePath is '/Users/Shubh/Documents/')
browser.driver.wait(function() {
        var fileName = filenamePath+"*.csv"
        var filesArray = glob.sync(fileName)
        if (typeof filesArray !== 'undefined' && filesArray.length > 0){
          return filesArray
        }
      }, 10000).then(function(filesArray) {
        var fileWithPath = filesArray[0]
        var temp = fileWithPath.indexOf("Pivot_Report")
        expect(fileWithPath.indexOf("Pivot_Report") >= 0).toBe(true,'Pivot Download is not succesfull')
        if(fs1.existsSync(fileWithPath)){
          fs1.unlinkSync(fileWithPath)
        }
      })
Getting the timeout error
It happens, because your path is incorrect.
I think easiest way is to use path.resolve() :
var path = require("path");
var filenamePath = path.resolve("Users/Shubh/Documents");
and then you will have (notice that you missed a / before *.csv)
var fileName = filenamePath+"/*.csv"

Swift XCTest load file

I'm getting confused and haven't been able to find any answers out there.
I have a TestClass in my Test Target. I put a file called test.csv into this target and on disk its stored in the same directory as all the other files.
What 3 lines of code do i need to load the file?
let bundle = NSBundle.mainBundle()
gives me this directory: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents and there doesn't seem to be anything in there.
Oh i figured it out:
NSBundle(forClass: <CLASSNAME>.self).URLForResource("Filename", withExtension: "extension")
Alternatively, returning the path as String:
NSBundle(forClass: <CLASSNAME>.self).pathForResource("Filename", ofType: "extension")

How to stop xcode debugger from mangling filesystem NSURLs on OS X?

I am trying to write a Mac app that converts files. I am stuck at the beginning because my app cannot open local files, at least while running in the debugger. I use the NSOpenPanel to create a valid file NSURL:
“file:///Volumes/Seagate_1tib/projects/dataskunk/wasteproduct.xml”
But somewhere in xcode, or the debugger or whatever, this gets mangled into
"/Users/charlweed/Library/Developer/Xcode/DerivedData/dataskunk-ghkiumvdkopxarhavynetidlqxio/Build/Products/Debug/file:/Volumes/bigdrive/dataskunk/wasteproduct.xml"
Reading the file then fails with a "No such file or directory error".
How do I prevent this mangling during development?
For example, this gives the error, no matter what file is chosen:
let fileResult = openFileDialog("Choose File", message:"Message")
let xmlInFileURLOpt: NSURL? = NSURL.fileURLWithPath(fileResult)
if let xmlInFileURL = xmlInFileURLOpt
{
var xmlFileError: NSError?
if !xmlInFileURL.checkPromisedItemIsReachableAndReturnError(&xmlFileError){
println("\(xmlFileError)")
return
}
}
The answer is that NSURL.fileURLWithPath() does not take a URL-path as an argument, only a filesystem-path. So "file:///Volumes/disk/file.xml" is wrong, "/Volumes/disk/file.xml" is correct.
The mangling is NSURL prefixing the current directory onto what it thinks is a relative filesystem-path String.

How to include file as resource in Xcode programmatically during build?

I have a file that is created by a script that is run during a build phase. Consequently, the file does not exist until build time.
How can I add the file to the app/project so that my code can access it at run time?
I know what the filename will be.
Normally, if I created the file by hand, I would just drag/drop it into Xcode, and I can instantly access it by using the filename in code. Since I am generating the file during build, I want to know how I can add it to my project.
EDIT: The file that I am adding is an Image file, that is created by a script during a build phase. I want to be able to access this file at runtime in my product.
I ended up using build references.
You could create the file and add it to the project and then during the build phase, your script could replace the existing file with the generated one....
The other option is to try manipulating the project file itself but that's quite complicated. Here are some resources on the subject...
You can copy the generated file to the build output using a script like this one I use to copy a plist with values maintained outside version control, as anything copied to "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/" is available using NSBundle APIs.
SECRETS="${SRCROOT}/../../secrets/Secrets.plist"
APP="${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/Secrets.plist"
if [ -f "$SECRETS" ]; then
cp -f "$SECRETS" "$APP"
echo "copied Secrets.plist: $APP"
else
echo "Secrets.plist not found at $SECRETS, all secrets will be 'MISSING'"
fi
For instance, that plist of secrets is defined as the Decodable struct SecretsFile and loaded with
private static var file: SecretsFile? = {
guard let url = Bundle.main.url(forResource: "Secrets", withExtension: "plist"),
let data = try? Data(contentsOf: url) else { return nil }
return try? PropertyListDecoder().decode(SecretsFile.self, from: data)
}()

Receiving the path of a VS2010 extension?

I've written a small Extension for VS2010 (vsix file), within the vsix is a binary file, which gets called by the extension.
I try to open the file like this:
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = #".\Binaries\TFPT.exe"}
Which works fine if I debug everything. But if I install it, I get a "file not found" error. The Binaries are installed correctly.
So I thought I try to get the complete path to the binaries. But how can I get the path? All Application.Path infos are not pointing to the correct path. Is there a way to get the path of the extension directory?
The path is something like:
C:\Users[username.domain]\AppData\Local\Microsoft\VisualStudio\10.0\Extensions[Company][ExtensionName]\1.0
Any idea without putting it together by hand?
How about retrieving the path from the current executing assembly and use Path.Combine() with your the remaining relative path segment ?
Note: This piece of code comes from a SO answer.
private static string RetrieveAssemblyDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
You can get this path asking for your extension installation path to Visual Studio:
var serviceProvider = [YourPackageObject] as IServiceProvider;
var manager = serviceProvider.GetService(typeof(SVsExtensionManager)) as IVsExtensionManager;
foreach (IInstalledExtension extension in manager.GetInstalledExtensions())
if(extension.Header.Name == [MyExtensionName])
return extension.InstallPath;

Resources