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 NSData+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.
Related
I am integrating Twilo sdk to my iPhone app.
NSString *urlString=#"urlstring";
NSURL* url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request startSynchronous];
NSString *response=[request responseString];
NSLog(#"Response:%#",response);
NSDictionary *dict=[response JSONValue];
NSMutableString *capabilityToken=[[NSMutableString alloc] initWithFormat:#"%#",[dict objectForKey:#"message"]];
device = [[TCDevice alloc] initWithCapabilityToken:capabilityToken delegate:nil];
I am getting response as
{"message":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJBQzYwYTFlOTMxOTI5NmFhNmFlZDcwZjhkYjZhMTQyNGJmIiwiZXhwIjoxMzM3NzU5MTA3LCJzY29wZSI6InNjb3BlOmNsaWVudDpvdXRnb2luZz9hcHBTaWQ9QVAxODRlNTE3YzZmN2EyZGI5NTkwMzM5N2I3NWRkMDliMSJ9.fXjQhBaXu3OlN_zXZIvSkoElphtQuW1QnNSbmUzfsSc"}
Assigning that string to TCDevice object while initializing I am getting following exception.
-[__NSCFString PJSTRString]: unrecognized selector sent to instance 0x77a21d0
Can anyone please help me the reason for this exception and how to solve it.
Thanks in advance.
Try adding the flags '-ObjC -all_load' to the "Other Linker Flags" in your target's Build Settings
Hi I have to send data to server via JSON and usually I do it like that:
NSMutableString * temp=[[NSMutableString alloc] initWithString:service_registra_inc];
//here I add more staff to temp
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:temp]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
but I get some error message that the url is wrong: something like url length but I have searched around and it means I have to escape my url si I have found this fonction that doesn't work for me:
NSString *temp2=(__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(NULL,((CFStringRef)temp.UTF8String),NULL,NULL,kCFStringEncodingUTF8);
and there the program just stops and it says signal EXC_BAD_ACCess.
Well I don't really know how to transform mutable strings into CFStringRef so xcode just suggested the corrections for me but I don't really understand what is happening. Please help.... I have read the doc but it doesn't say how to cast NSSMutableString to CFStringRef and back or how to use the whole thing to create an NSURL object directly. Thks
Why are you using CFURL & CFStringRef functions here?
You could do what you are trying to do via NSString's stringByAddingPercentEscapesUsingEncoding: method. I've linked the documentation for you.
Something like:
NSMutableString * temp=[[NSMutableString alloc] initWithString:service_registra_inc];
// append your staff... errr, stuff here.
NSString * temp2 = [temp stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:temp2]];
[NSURLConnection alloc] initWithRequest:request delegate:self];
(don't forget to release things if you're not using ARC)
An NSString * is also a CFStringRef through a mechanism known as toll-free bridging and an NSMutableString * is also an NSString * through inheritance. So your second line of code should be:
NSString *temp2 = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)temp,
NULL,
NULL,
kCFStringEncodingUTF8);
Though in practice you might prefer:
NSString *temp2 =
[temp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Which has the secondary advantage of returning an object with a non-owning reference, so you don't need to worry about releasing it even if you're not using ARC.
I have a simple POST coming from my iphone app. Its working fine, except passing an ampersand causes the backend to break - it's almost like its treating it like a GET request (ampersands seperate the variable names). Do I need to do some kind of encoding first? Here is the code:
NSString *content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", str, emailAddress.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.myurl.com/myscript.php"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
I had this issue in iOS7 and the accepted answer didn't work at all (actually, that is my standard when sending data to the backend). The ampersand was breaking in the backend side, so I had to replace the & by %26. The backend was being done in python and the code was legacy and was using ASI.
Essentially I have done the following:
NSString *dataContent = [NSString stringWithFormat:#"text=%#",
[json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dataContent = [dataContent stringByReplacingOccurrencesOfString:#"&"
withString:#"%26"];
ByAddingPercent....... will not work as & is a valid URL character.
I needed to send a JSON with & in it, it is the same idea though;
NSString *post = [NSString stringWithFormat:#"JSON=%#", (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)jsonString, NULL, CFSTR(":/?#[]#!$&’()*+,;="), kCFStringEncodingUTF8))];
"jsonString" towards the end is what is converted.
Edit: As stringByAddingPercentEscapesUsingEncoding: should be used to encode parts of the query, not the whole one, you should be using another method instead.
Unfortunately, Foundation doesn't provide such a method, so you need to reach to CoreFoundation:
- (NSString *)stringByURLEncodingString:(NSString *)string {
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL, // or (__bridge CFStringRef)(#"[].")
(__bridge CFStringRef)(#":/?&=;+!##$()',*"),
kCFStringEncodingUTF8
);
}
You can use
- stringByAddingPercentEscapesUsingEncoding:
In your case it will look like this:
NSString * content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [emailAddress.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
You can do this in this way, too:
NSString *dataStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *emailStr = [emailAddress.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", dataStr, emailStr];
I'm not sure if this will work in your case, but you could try %38 to try and encode the ampersand.
I am trying to send a query as part a the URL to obtain an XML file, and then trying to parse the XML file using NSXMLParser and initWithContentsOfURL. However the parser is not able to parse the file. I tested the parser with the same file, but this time the file was saved on the server (it was not being generated) and it worked just fine, so I know it is not a problem with the parser.
I have come to think that it does not parse it because I need to load the file before I try to parse it, or give the initWithContentsOfURL time to load the contents. So I tried to put those contents in a NSString and a NSData and using a sleep function as well as using a block but that did not work either.
What would be the best way to go about this problem?
Here is some of the code:
NSString *surl = [NSString stringWithFormat:#"http://lxsrv7.oru.edu/~maria_hernandez/query.xml"];
url = [NSURL URLWithString:surl];
NSString *curl = [[NSString alloc] initWithContentsOfURL:url];
NSLog(#"URL: %#", surl);
NSLog(#"URL Content: %#", curl);
SXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:receivedData];
//Other stuff we have tried:
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:surl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLResponse = nil;
NSError = nil;
receivedData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &theResponse error: &error];
Let me know if you have more questions or if you wish to see more code.
Thanks!
have you tried setting a delegate for the NSXMLParse that implements the NSXMLParserDelegate which has events for parsing the document
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html
I am trying to parse a JSON response of a GET request. When the characters, are latin no problem.
However when they are not latin the message doesn't come out correctly. I tried greek and instead of "πανος" i get "& pi; & alpha; & nu; & omicron; & sigmaf;"
The code I use for parsing the response is:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response %#", responseString);
// array from the JSON string
NSArray *results = [responseString JSONValue];
When I try to read the response from a website using ajax, everything is fine. The same applies when trying to send a GET request to the application servers with data from iphone. So when i transmit data to the server and read it from the website everything is fine. When i try to show the same data in the app, "Houston we have a problem".
Any clues?
EDIT: To avoid misunderstandings, it's not an issue of HTML, I just point out that for some readon utf-8 characters here are encoded correctly and automatically eg. "&pi" will be converted to "π", however objective c doesn't seem to do this on its own
There is a confusion I think.
π is an HTML entity which is unrelated to text encoding like UTF8 / Latin.
Read wikipedia for details about...
You need a parser to decode these entities like the one previously mentioned by Chiefly Izzy:
NSString+HTML category and method stringByReplacingHTMLEntities
Look at Cocoanetics NSString+HTML category and method stringByReplacingHTMLEntities method. You can find it at:
https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSString%2BHTML.m
Here's a pretty decent list of lot of HTML entities and their corresponding unicode characters.
Try to use this snippet of code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *decodedString = [NSString stringWithUTF8String:[responseString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSLog(#"response %#", decodedString);
// array from the JSON string
NSArray *results = [decodedString JSONValue];
I have faced the same problem, but I solved it by changing the JSON parser. I have started using the SBJSONParser, and now I am getting the appropriate results. This is the code snippet, I have used
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
SBJSON *parser=[[SBJSON alloc]init];
NSArray *JSONData = (NSArray*)[parser objectWithString:returnString error:nil];