I'm adding a Basic HTTP Authorisation Header into a request but need to encode the authString to Base64. For info, I can't use didReceiveAuthenticationChallenge due to excessive 401 errors being produced.
The code below works fine in iOS 4.2 but doesn't work on iOS 3.2 (and I want to support this).
NSString *authString = [[[NSString stringWithFormat:@"%@:%@", user, password] dataUsingEncoding:NSUTF8StringEncoding] base64Encoding];
authString = [NSString stringWithFormat: @"Basic %@", authString];
NSMutableURLRequest* request =
[[NSMutableURLRequest alloc] initWithURL: url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 30];
[request setValue: authString forHTTPHeaderField: @"Authorization"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
In the first line of my code above I get the warning that NSData will not respond to 'base64Encoding'.
So I've downloaded the custom class NSDa开发者_Go百科ta+Base64 from here: http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
But......I don't know how to use this class to convert my NSString (authString). Please help?!
I think the following line of code should fix:
NSString *authString = [[[NSString stringWithFormat:@"%@:%@", user, password] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
but I get following message:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableData base64EncodedString]: unrecognized selector sent to instance
Have I missed an Import or something?
P.S. This is my first question on here, so go easy on me!!
NSString
has a -dataUsingEncoding:
method which you can use to convert NSString
instances to NSData
instances. After that, you can use MG's Base64 category.
Have you created the category to use the BASE64Encoding method in your NSData class?? here i made a tutorial to easy create categories, which basically are modifications of an existing class, in this case NSData: http://www.donttouchmycode.com/objective-c-class/extending-an-existing-class-with-categories i hope this can help you.
精彩评论