What do I do with NSData? - cocoa

I am trying to send email programmatically... I have this line of code:
_mail.AddAttachmentData(nsd,"text/plain", filePath);
and I haven't a clue what goes into NSData... I tried taking the string that I was writing to a file, but apparently that doesn't work either. I believe it is preventing me from doing a good sendmail.

NSData is a class type. See here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html
You'll probably want to construct your NSData object using something like this:
NSString *myFilePath = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"txt"];
NSData *myData = [NSData dataWithContentsOfFile:myFilePath];
Then pass that in as the NSData object.

Related

NSURLThumbnailDictionaryKey empty for local file

I want to get a thumbnail representation of a file I have to display in my app. I'm using NSURL here:
NSDictionary *thumbnails = nil;
BOOL success = [fileURL getResourceValue:&thumbnails
forKey:NSURLThumbnailDictionaryKey
error: &error];
This works fine if I am connected to iCloud, and the URL is a link to a file stored in iCloud. The fileURL is something like:
file:///Users/me/Library/Mobile%20Documents/BJXXGLR9R3~com~myapp~icloud/FileStorage/contact-page%20copy.png
If I use the same code with a NSURL pointing to a local file, however, the thumbnails dictionary is empty.
Here is an example of the URL in this case:
file:///Users/me/Library/Containers/com.mycompany.mymacapp/Data/Library/Application%20Support/com.mycompany.mymacapp/FileStorage/Bn4VaCnCUAEJjLb.png-large.png
Is this API for getResourceValue not supposed to work with locally stored files? Or am I doing something wrong?
This is part of the API. Furthermore you should use a File coordinator while working with files coming from iCloud:
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
__block NSError *error;
[coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
[newURL getResourceValue:&image forKey:NSURLThumbnailDictionaryKey error:&error];
}];
[url stopAccessingSecurityScopedResource];

dictionaryWithContentsOfFile and Sandbox

I've created a mac app that load a xml file from an user selected folder, and after using the app, the user saves a customized file (.adgf)
When i try to load the .adgf file (that is a plist file) that has the xml path within one record i call
dictionaryWithContentsOfFile but it return me a "nil". I think the problem is the sandbox (sometime it works sometime not). The string path is correct.
Maybe when the user load the xml file should i save within of particular app "Document folder"?
Edit:
I'm trying right now the Bookmark Data solution and I retraive a NSURL but it doen't work. The code I'm using is this:
- (NSData *)bookmarkFromURL:(NSURL *)url {
NSError *error = nil;
NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys:NULL
relativeToURL:NULL
error:&error];
if (error) {
NSLog(#"Error creating bookmark for URL (%#): %#", url, error);
[NSApp presentError:error];
}
return bookmark;
}
- (NSURL *)urlFromBookmark:(NSData *)bookmark {
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark
options:NSURLBookmarkResolutionWithSecurityScope
relativeToURL:NULL
bookmarkDataIsStale:NO
error:NULL];
return url;
}
After the user stores the file you should take the bookmark data from the URL using
-[NSURL bookmarkDataWithOptions: includingResourceValuesForKeys: relativeToURL: error:]
Use NSURLBookmarkCreationWithSecurityScope for the options.
This NSData object should be stored somewhere (plist?) and when you want to read the file again in a later session you can create a sandbox compliant NSURL from the bookmark data using +[NSURL
URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:]

NSURLRequest with UTF8 password

Here is a method I've written to connect to a server and get a user auth token:
+ (void)getAuthTokenForUsername:(NSString *)username
password:(NSString *)password
completionHandler:(void (^)(NSString *, NSError *))completionHandler
{
username = [username URLEncodedString];
password = [password URLEncodedString];
NSString *format = #"https://%#:%##api.example.com/v1/user/api_token?format=json";
NSString *string = [NSString stringWithFormat:format, username, password];
NSURL *URL = [NSURL URLWithString:string];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:URL]
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *URLResponse, NSData *data, NSError *error)
{
NSString *token;
if (data) {
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
token = [NSString stringWithFormat:#"%#:%#", username, dictionary[#"result"]];
}
completionHandler(token, error);
}];
}
A URL then looks something like this: https://username:hello%C2%B0#api.example.com/v1/user/api_token?format\=json, where the password is hello°. The URLEncodedString method properly encodes everything as in the example, but the request never works. The problem is not with escaping or the server, because I can curl the same URL and I get nice JSON and authentication works, even though there is a non-ASCII character in the password. It also works from other programming languages like ruby or python. But the same url never works with NSURLConnection and it also doesn't work in Safari, which of course uses NSURLConnection. I get an 'The operation could not be completed' with a '401 Forbidden' every time.
(My code works fine when the password just contains ASCII characters. I also tried using the NSURLCredential methods, same problem.)
What do I need to do for NSURLConnection to work with such a URL as https://username:hello%C2%B0#api.example.com/v1/user/api_token?format\=json where the password contains non-ASCII characters?
I have just performed several tests against my mockup server and I think I have a solution for you.
First of all, when you add username & password to an URL, they are not actually send to the server as part of the URL. They are sent as part of the Authorization header (see Basic access authentication).
The fastest workaround for you is to do
NSURLRequest* request = [NSURLRequest requestWithURL:URL];
NSString* usernamePassword = [[NSString stringWithFormat:#"%#:%#", username, password] base64Encode];
[request setValue:[NSString stringWithFormat:#"Basic %#", usernamePassword] forHTTPHeaderField:#"Authorization"]
To understand the problem, let's go a bit deeper. Let's forget NSURLConnection sendAsynchronousRequest: and let us create an old-fashioned connection with a NSURLConnectionDelegate. Then in the delegate, let's define the following methods:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(#"Proposal: %# - %#", challenge.proposedCredential.user, challenge.proposedCredential.password);
NSURLCredential* credential = [NSURLCredential credentialWithUser:#"username"
password:#"hello°"
persistence:NSURLCredentialPersistenceNone];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
}
If you don't create these methods, the username & password from your URL won't ever be added to the HTTP header.
If you add them, you'll see that the proposed password is hello%C2%B0. Obviously, that's wrong.
You can see the problem directly from
NSLog(#"Password: %#", [[NSURL URLWithString:#"http://username:hello%C2%B0#www.google.com"] password]);
which prints
hello%C2%B0
I believe this is a bug in the framework. NSURL returns password encoded and NSURLCredential doesn't decode it so we are left with an invalid password.

What is the encoding for URL bookmarks stored as NSData?

What is the best way to get the path from the NSData bookmark object, if the bookmark will not resolve?
Normally, you just resolve the bookmark, you get a URL, and off you go. But if the bookmark is to an NFS mount that is not currently present, it won't resolve. So now I have an NSData pointing somewhere that won't resolve, but I don't know where it points.
Here is the code block I have that loads the bookmarks, tries to resolve them, and attempts to decode the NSData if the resolve fails, but I can't figure out the encoding - is this even possible?
NSError* error = [[NSError alloc] init];
NSURL* resolvedURL = [NSURL URLByResolvingBookmarkData:bookmarkData
options:NSURLBookmarkResolutionWithSecurityScope | NSURLBookmarkResolutionWithoutUI
relativeToURL:nil
bookmarkDataIsStale:NULL
error:&error];
if (resolvedURL) {
// do some stuff
...
} else {
NSString* msg = [NSString stringWithFormat:#"Error Resolving Bookmark: %#", error];
NSLog(msg);
// the below certainly doesn't get me a path from the bookmark, any idea what will?
// NSString* path = [[NSString alloc] initWithData:bookmarkData encoding:NSUTF32StringEncoding];
}
I never did figure out the encoding, but I found a workaround.
Originally, I encoded the sandboxed NSURLs into NSData objects, and then stored those as an NSArray in NSDefaults. Therefore, I had no way to determine the path for the NSData, unless it would resolve.
The workaround was to change the design - now I encode the sandboxed NSURL, store it as an object into an NSDictionary with the key being the URL path, and store the NSDictionary in NSDefaults.
With this approach, I can easily retrieve the NSData for any given path, even if it will not resolve.

What does -[NSURL length]: unrecognized selector sent to instance 0x1001c0360 mean

I've been trying to get some example code interfaced with a Cocoa interface(It had been written using Carbon); however, when I attempted to replace
err = ExtAudioFileCreateNew(&inParentDirectory, inFileName, kAudioFileM4AType, inASBD, NULL, &fOutputAudioFile);
with
err = ExtAudioFileCreateWithURL(CFURLCreateWithString(NULL,(CFStringRef)inFileName,NULL),kAudioFileM4AType,inASBD, NULL,kAudioFileFlags_EraseFile, &fOutputAudioFile);
I started to get these exceptions
2011-09-25 10:27:31.701 tester[1120:a0f] -[NSURL length]: unrecognized
selector sent to instance 0x1001c0360
2011-09-25 10:27:31.701 tester[1120:a0f] -[NSURL length]: unrecognized selector sent to instance 0x1001c0360.
I've looked at several other questions and answers and in all of those cases the problem was related to a NSURL being passed when a NSString was expected; however, I can't find where/if I'm doing that. I've looked at the documentation and as far as I can tell with my extremely limited knowledge of Apple's APIs. I'm not doing anything wrong.
Any help would be greatly appreciated.
May be help you, i had same problem
I was trying to make UIImage from :
[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
Then its solved with by making string with [NSString stringWithFormat:]
NSString *urlStr =[NSString stringWithFormat:#"%#", [_photosURLs objectAtIndex:indexPath.row]];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
The error message is pretty clear. NSURL class does not have a -length instance method.
Have you tried to create the NSURL object with Objective-C syntax and cast it to CFURLRef?
I had the same issue while getting url from string like
[NSString stringWithFormat:#"%#Activity/GetBudget/%#",self.baseURL,activityID]
and I resolved it by calling absoluteString
like this
[[NSString stringWithFormat:#"%#Activity/GetBudget/%#",self.baseURL,activityID] absoluteString]

Resources