NSBundle bundleWithPath fails - objective-c

I am trying to load a bundle using bundleWithPath but it always fails (returns nil)
I was wondering what can be teh reasons why it fails and what are the way to het more information about the error.
Thanks in advance for your help!
Regards,

The failure may have many reasons: the file doesn't exist, the file exist but not in the path you are looking for. It has some different extention. Or the file at your path is not in correct bundle format. That's all I can tell you without code.
From the documentation:
+bundleWithPath:
Returns an NSBundle object that corresponds to the specified directory.
+ (NSBundle *)bundleWithPath:(NSString *)fullPath
Return Value: The NSBundle object that corresponds to fullPath, or nil if fullPath does not identify an accessible bundle directory.

Related

creating a folder and verifying that the path is ok

I want to create a folder in my VB .NET app but I can't get to verify that the path is correct. For example, if I enter
My.Computer.FileSystem.CreateDirectory("lol it will work")
It works... While it doesn't look like a folder path at all... How can I verify that the path entered is correct ? And since it doesn't throw any exception, the folder must be created somewhere, but where ? I can't find it...
Thank you
Your Directory name "lol it will work" is a valid name.
When you don't provide an explicit path, My.Computer.FileSystem.CreateDirectory() (as well as some other methods/functions) will assume the string you provided is the path to a directory which relative path is your Application's current directory.
So it doesn't matter whether you're passing a complete path (that looks like a valid folder path) or a partial path/folder name that will be associated with the application's Directory as long as :
the resolved Path is a valid path (that doesn't contains invalid chars or missing folder name separator)
you (your application) have access to that path
the resulting path doesn't exceed the max allowed number of characters.
you don't encounter some specific Exceptions...
So, how do you know your application current working path ?
Since you used My.Application.FileSystem :
My.Computer.FileSystem.CurrentDirectory ' Read/Write Property As String
You can use System.IO :
System.IO.Directory.GetCurrentDirectory() ' Get a String
System.IO.Directory.SetCurrentDirectory(NewPath) ' Set
You can also use System.Environment.Directory
Environment.CurrentDirectory ' Read/Write Property As String
Both three (My.Computer.FileSystem, System.IO.Directory and Environment) are writable, and returns the current directory to be resolved in case you're providing relative paths in your application.
So, to answer your question : "How can I verify that the path entered is correct ?"
If you just created the Directory and you get no exception, then the name of your (relative) directory is valid, and the directory has been created :
My.Computer.FileSystem.CreateDirectory("lol it will work")
' Verification :
If System.IO.Directory.Exists("lol it will work") Then
MessageBox.Show("The Directory has been created !")
Else
MessageBox.Show("The Directory has'n been created !")
End If
' Shows "The Directory has been created !"
So you know that even other Functions/Methods can resolve relative path (not all though) by fallbacking to the defined Relative Working Path of your Application.
The test above is the same as :
System.IO.Directory.Exists( _
Path.Combine(Environment.CurrentDirectory, "lol it will work"))
CAUTION :
Due to the writable nature of those objects, your application
may change the Current Directory any time.
Consider :
the use of alternative objects/variables to get your working directory or similar
working with only explicit paths
using a global/static variable that stores the CurrentDirectory upon startup (can fail very easily)
restoring the CurrentDirectory whenever you're changing it (though you will use at a time or another an object that changes the CurrentDirectory without warning - read the documentation of that object whenever it involves a directory manipulation; OpenFileDialog for example which has different behaviours on XP and Win7/8) - This move is the least recommended.
Alternates :
AppDomain.CurrentDomain
AppDomain.CurrentDomain.BaseDirectory
This is a ReadOnly Property. It returns the path to the directory your assembly (application) were loaded from. Caution ! This path has a trailing "\" like :
G:\Tools\...\Sources\bin\Debug\ ' <- !!!
Assembly.GetExecutingAssembly().Location
System.IO.Directory.GetParent(Assembly.GetExecutingAssembly().Location)
This will also return the path to the directory the assembly were loaded from, but without the trailing "\" due to the use of GetParent()
Using Assembly to retrieve a path is useful when you're dealing with dependencies where not all Assemblies are loaded from the same directory. Codes that uses relative paths should use this approach instead of the classic ones.
I assume the same applies for Thread Domain if you want to get deep in multithreads (while I'm not really sure of the relevant aspect of this assumption - Never used this one !) :
Thread.GetDomain().BaseDirectory ' ReadOnly
And the good old Application.StartupPath
Application.StartupPath ' ReadOnly
...which also has a trailing "\". You can't access StartupPath until the application has actually started ! However, I've never checked whether it's working well when you start another process from your application and using that through the other process... (if it's possible... just imagining though)

How to export package files in document based application on OSX?

in my app, I want to load certain image user picks, make some modification, after that, save a copy in my own file format. Since I want to keep track of user modification, I decided to export my file as a package(bundle).
So, in my document class, there's a NSImage object that holds the image file. In the fileWrapperOfType:error: method, I've setup a NSFileWrapper object, and put the object in it. Here's the code:
NSDictionary *fileWrappers = [self.documentFileWrapper fileWrappers];
if (image != nil) {
NSBitmapImageRep *imageRep = [image bitmapImageRepresentation];
NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
NSFileWrapper *imageFileWrapper = [[NSFileWrapper alloc]
initRegularFileWithContents:imageData];
[imageFileWrapper setPreferredFilename:#"image"];
[[self documentFileWrapper] addFileWrapper:imageFileWrapper];
}
return self.documentFileWrapper;
In my project plist file, I have two document types, first is the type of public.image since I need to load images in my app:
The other one is my own document type. To make the file a package, I've checked the bundle checkbox in xcode:
If I simply run this now, the code compains that finding extension from type identifier is deprecated, so, I managed to add an entry in Exported UTIs:
At this moment, everything seems working, except that the outputed folder with mdc extension, is indeed a folder instead of a package, what am I missing here? Thanks in advance!
Finally I solved the problem, the key here is to change Conforms To field to com.apple.package.
In order for a package on OS X to be a pkg, it must have a .pkg extension. I hope it is as simple as having the wrong extension.
Note: Until recently, .pkg files were merely directories. Now, we often see package.pkg packages that are obscured cannot be browsed causually without some tricks like using Pacifist, pkgutil or xar:
pkgutil --extract file.pkg folder/
or
xar -xf file.pkg

Get path of App_Data folder in the Seed method of EF migration configuration class

How do you get the path of the App_Data folder in the Seed method of the configuration class of code first migrations.
I want to read from a file I've put in the App_Data folder and the Seed method runs after the update-database command. HttpContext.Current.Server.MapPath obviously does not work because there is no HttpContext at that point.
I got it to work with something like:
string MyPath = AppDomain.CurrentDomain.BaseDirectory + "/../App_Data"
because AppDomain.CurrentDomain.BaseDirectory ends at the "/bin" directory.
Here is a quick-and-dirty way to get you started:
var myPath = AppDomain.CurrentDomain.BaseDirectory;
//to quickly show the path, either attach another debugger or just throw an exception
throw new Exception(myPath);
#Rusty Divine gave a good answer, however maybe you will find this is better for you:
System.IO.Path.Combine( System.Text.RegularExpressions.Regex.Replace(AppDomain.CurrentDomain.BaseDirectory, #"\\bin\\Debug$", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase) , RELATIVE_PATH, "FILENAME.EXE");
For example:
System.IO.Path.Combine( System.Text.RegularExpressions.Regex.Replace(AppDomain.CurrentDomain.BaseDirectory, #"\\bin$", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase) , "App_Data\\Init", "fileName.txt");
In that way (using Regx), we make sure the only replace could be is at the suffix (at the end) of the AppDomain.CurrentDomain.BaseDirectory String. If there is sub folders in the server path named: "\bin\Debug" they won't be replaced.
This solution is case insensitive, meaning "\BIN\debug" will also be replaced.
Moreover, you don't need to append the strings to one string.
System.IO.Path.Combine will do it for you.
For what it's worth... you need to do a string replace if you are going to use BaseDirectory in your unit test. But, this still has the problem that it uses the path of your unit test project so be weary of that if you are trying to point to files in another project. In this case you will have to hard code the path.
AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug","") + "\\App_Data";

ASIHTTPRequestErrorDomain Code=8. Cannot move file from temp directory to docs

I download files with ASIHTTPReqeust. Everything downloads fine but it can't move file from temp directory to documents. When i implement
-(void) request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
request fails with an error. But file is downloaded.
If i remove this implementation, everything is fine, and files are moving to docs.
Here is Error text:
Error Domain=ASIHTTPRequestErrorDomain Code=8 "Failed to move file from '/var/folders/Qu/Qu0o0VcpEY4npJr2C1yPzE+++TI/-Tmp-/Skrillex feat. Nero - Wobbleland.mp3' to '/Users/Timur/Library/Application Support/iPhone Simulator/4.3/Applications/34389282-4013-4354-95D9-DF2847B4EE55/Documents/Audio/Skrillex feat. Nero - Wobbleland.mp3'" UserInfo=0x5949520 {NSUnderlyingError=0x59992a0 "The operation couldn’t be completed. (Cocoa error 4.)", NSLocalizedDescription=Failed to move file from '/var/folders/Qu/Qu0o0VcpEY4npJr2C1yPzE+++TI/-Tmp-/Skrillex feat. Nero - Wobbleland.mp3' to '/Users/Timur/Library/Application Support/iPhone Simulator/4.3/Applications/34389282-4013-4354-95D9-DF2847B4EE55/Documents/Audio/Skrillex feat. Nero - Wobbleland.mp3'}
Who had similar problem?
Something that often catches people out is that you have to create the directory that you're downloading into yourself (ASIHTTPRequest won't create it automatically).
However given you say it's related to the implementing didReceiveData it's not that.
If you look at ASIHTTPRequest.m, you'll see it sets 'dataWillBeHandledExternally' if you implement 'didReceiveData' in the delegate - this will be preventing the data being written to disk. You can either write the data yourself, or you could change the ASIHTTPRequest.m code to add a flag to force it to handle the data internally too.
I encountered same error, but the reason was different. I will post my problem - just in case anyone else has similar situation.
I was trying to delete old images, before saving new ones.
NSString *mImgName = [managedObj valueForKey:#"aImgName"];
NSString * mFilePath = [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:mImgName];
if ([mFileManager fileExistsAtPath:mFilePath])
{
[mFileManager removeItemAtPath:mFilePath error:nil];
}
Problem was - in case mImgName is nil, mFileManager will delete whole directory.
By adding extra checking for nil or too short mImgName value, it solved problem.
Hopefully it will help someone!

NSAppleScriptErrorNumber = -1708

I am trying to attach a Image to Mail application using Applescript. But on 10.5 I am getting
NSAppleScriptErrorNumber = -1708 error. What is this error means?
Can anybody guide me with this?
Regards,
Sowmya
I wrote an applescript that tells you what the error codes mean. Get it here. Look in post #9 for the most recent version I posted.
As Philip Regan says. More info needed.
But I suspect its your construction of the file paths.
I have used NSAppleScript in the past to attach files to mail. If I remember right. My app gathered the files path as a Unix type path string.
i.e /Users/UserName/Documents/myFile.ext.
And in the NSApplescript script string I use "POSIX file \"%#\") as alias"
NSString *scriptString= [NSString stringWithFormat:#"set theMailname to (POSIX file \"%#\") as alias\ntell application \"Mail\"\nset newMessage to make new outgoing message with properties{visible:true,subject:\"%#\", content:\"%#\"}\ntell newMessage\nset visible to false\n\nmake new to recipient at end of to recipients with properties {address:\"%#\"}\n set theAddressFrom to \"%#\"\ntell content\nmake new attachment with properties {file name:theMailname} at after the last paragraph\nend tell\n save \nend tell\nend tell",fileStore,subject,body,theAddressTo,theAddressFrom];
fileStore being the unix type path of the file that is converted to an Alias.