String won't url encode in iOS - objective-c

I'm seriously having a brain fart here, but I can't figure out why this isn't encoding for the life of me. Been searching all over, and I can't even get the code samples to encode. Any ideas?
NSString *searchString = #"waffl&es";
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"http://en.wikipedia.org/?search=%#", encodedSearchString];
NSURL *url = [NSURL URLWithString:urlString];

For future reference, this is what I found to work (i.e. encode everything properly)
+ (NSString*)encodeURL:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
if (newString)
{
return newString;
}
return #"";
}

Related

IOS 10 Xcode 8 NSString From NSDictionary returns nil

This feels like a bug, this code worked perfect before iOS 10.
Has anyone noticed anything similar?
heres the code.
NSString *path = [[NSBundle mainBundle] pathForResource:className ofType:#"plist"];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
NSDictionary *animationSettings = plistDictionary[animationName];
float delayPerUnit = [animationSettings[#"delay"] floatValue];
NSString *animationFrames = animationSettings[#"animationFrames"];
// NSString is empty here
NSArray *animationFrameNumbers = [animationFrames componentsSeparatedByString:#","];
// NSArray is empty because NSString is empty.
I found a workaround
NSString *path = [[NSBundle mainBundle] pathForResource:className ofType:#"plist"];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
NSDictionary *animationSettings = plistDictionary[animationName];
float delayPerUnit = [animationSettings[#"delay"] floatValue];
NSString *animationFrames = animationSettings[#"animationFrames"];
// If I add 1 to animationFrames, then everything works fine.
if (!animationFrames) {
animationFrames = [NSString stringWithFormat:#"1"];
}
NSArray *animationFrameNumbers = [animationFrames componentsSeparatedByString:#","];
Not Sure if this is a bug, or I'm doing something wrong. thanX for the help!!! :D

Contents from url to string

NSString *urlAddress = [NSString stringWithFormat:#"http://www.domain.com?input=%#",[alertView textFieldAtIndex:0].text];
NSURL *myUrl = [NSURL URLWithString:[urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *openURL = [NSString stringWithContentsOfURL:myUrl encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#",openURL);
openUrl is always returning (null), probably because of the encoding, but I don't know how to fix it.
Double check these three things:
Check that the URL which you are pointing to is a valid URL. The null value could be a result of an invalid URL.
Catch the NSError which the stringWithContentsOfURL throws. That will give you some insight on what is wrong.
Like you suspect, try changing the string encoding.
NSError *error;
NSString *urlString = [NSString stringWithFormat:#"http://www.domain.com?input=%#", stringVariable];
NSURL *urlAdress = [NSURL URLWithString:urlString];
NSString *urlContent = [[NSString alloc] initWithContentsOfURL:urlAdress encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", urlContent);
This works fine, the problem was an failing internet connection.

UItextFields Data to JSON

i have two UItextFields, userNameTextField and passwordTextField and a UIbutton connection. I would like to have what the user typed in the userNametextField and the passwordTextField, How i can do this please ?? thanks for your answer.
#pragma mark - User auhtentification
-(IBAction)userAuthentificate{
BOOL loginValid = YES;
BOOL passwordValid = YES; // Not specified yet
// contrioll d'interfac__ on test login et password
if (loginValid && passwordValid) {
NSString *jsonRequest = #"{\"login\":\"Samir\",\"password\":\"test\",\"mail\":\"test#gmail.com\"}";
// NSString *jsonRequest = #"{\"login\":\"Samir\",\"password\":\"test\",\"mail\":\"samir#gmail.com\",\"editor\":\"1\"}";
NSString *request_url =#"http:.../register"; // Url WS
NSURL *url = [NSURL URLWithString:request_url];
self.currentRequest = [ASIFormDataRequest requestWithURL:url];
currentRequest.delegate =self;
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[self.currentRequest appendPostData:requestData];
[self.currentRequest setRequestMethod:#"POST"];
[self.currentRequest startSynchronous];
}
}
You can put something like this in the place of your jsonRequest string (the code uses the SBJson framework):
NSDictionary *container = [[NSDictionary alloc] initWithObjectsAndKeys:
[loginTextField text], #"login",
[passwordTextField text], #"password",
[mailTextField text], #"mail"];
NSString *jsonString = [container JSONRepresentation];
// don't forget to release container if not using ARC AFTER creating the NSData object
How about a simple string replacement?
NSString *jsonRequest = [NSString stringWithFormat:#"{\"login\":\"%#\",\"password\":\"%#\",\"mail\":\"%#\"}", userNameTextField.text, passwordTextField.text, emailtextField.text];
Use
NSString *jsonRequest = [NSString stringWithFormat:#"{\"login\":\""%#"\",\"password\":\""%#"\",\"mail\":\"test#gmail.com\"}",userNameTextField.text,passwordTextField.text];

encode a NSString setHttpPostBody for nsurlconnection

String content = "username="+ URLEncoder.encode(username, UTF_8_TYPE);
want to do a similar in objectiveC
NSString *body = [NSString stringWithFormat:#"username=%#", [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURL returns Nil Value

Here Below is my code
NSString *string = [NSString stringWithFormat:#" http://abc.com /Demo/View.php?drinkId=%#&name=%#&comment=%#&date=%#&rating=%#& ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];
NSURL *url = [[NSURL alloc] initWithString:string];
Here in string there is value but url returns nil.
Can Anyone tell why this happened.
Thanks ....
"This won't work, so here's what I did instead"
NSString *string = [NSString stringWithFormat:#"http://abc.com/Demo/View.php?drinkId=%#&name=%#&comment=%#&date=%#&rating=%#&ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];
NSURL *url = [[NSURL alloc] initWithString:string];
NSURL will return nil for URLs that contain illegal chars, like spaces.
Before using your string with [NSURL URLWithString:] make sure to escape all the disallowed chars by using [NSString stringByAddingPercentEscapesUsingEncoding:].
Here is the class reference for NSString.
Hi All Now My Problem Is solved here I did a mistake left a blank space before "http".
The correct code is
NSString *string = [NSString stringWithFormat:#"http://myserver.com/Demo/View.php?drinkId=%#&name=%#&comment=%#&date=%#&rating=%#&ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];
NSURL *url = [[NSURL alloc] initWithString:string];