In my app i have a service which supports spanish and return the result in spanish.
Now i am trying to pass some search term to this service to get the result back but its failing because while sending compiler converts the word to some funny word with unidentified characters.
I am doing this:
name here is coming in spanish but when i am adding this in the config dictionary it gets converted again to some funny thing.
-(void)perfromLocationSearchWithName:(NSString *)name{
NSData * nameCode = [[NSData alloc]init];
nameCode = [name dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString * namePass = [[NSString alloc]initWithData:nameCode encoding:NSUTF8StringEncoding];
NSLog(#"Name:%#",namePass);
NSMutableDictionary *config = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
NSString * strAction = [NSString stringWithFormat:#"vendorSearchByName"];
if (namePass !=nil){
[config setObject:namePass forKey:#"vendorName"];
//[config setObject:#"001" forKey:#"MakeCode"];
[config setObject:#"5" forKey:#"maxCount"];
[config setObject:strAction forKey:#"action"];
}
NSLog(#"Dict%#",[config description]);
comm = [[CommManager alloc] init];
[comm searchDealerLocationWithOptions:config withDelegate:self];
[namePass release];
}
Please help
Thanks,
Try using NSISOLatin1StringEncoding. Helped us in our app.
Related
How should i convert the emojis into unicode and send it to server and then can decode it dynamically.
I can statically give the if condition for perticular emojis.But i want to make it dynamically.
Thanks in advance
few days ago i have same problem. i tried this its work for me :
to pass value to the server
NSData *data = [textView.text dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodValue = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
goodValue = [goodValue stringByReplacingOccurrencesOfString:#"\\" withString:#"\\\\"];
when fetch value from the server
NSString *goodValue = [StaticClass urlDecode:[dataDict objectForKey:#"comment_text"]];
NSData *newdata=[goodValue dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *mystring=[[NSString alloc] initWithData:newdata encoding:NSNonLossyASCIIStringEncoding];
I want to create a url as below
http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false
I used the following code to create this
NSURL *jsonURL;
NSString *strurl = [[NSString alloc]initWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false"];
jsonURL = [NSURL URLWithString:strurl];
[strurl release];
NSLog(#"json Url%#",jsonURL);
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
if(jsonData == nil){
//NSLog(#"Data NIL .....");
}
else{
SBJSON *json = [[SBJSON alloc] init];
NSError *error = nil;
dic = [json objectWithString:jsonData error:&error];
[json release];
}
But every time I get jsonURL to be nil .
I think the problem is due to "|". Has someone come across same issue? If yes, can you help me out?
Try
[NSURL URLWithString:[strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
The documentation for URLWithString says:
The string with which to initialize the NSURL object. Must conform to RFC 2396.
... which e.g. mentions:
Other characters are excluded because
gateways and other transport agents
are known to sometimes modify such
characters, or they are used as
delimiters.
unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
Data corresponding to excluded
characters must be escaped in order to
be properly represented within a URI.
Thus escape them properly as slf suggested.
Also, just use a string constant for predefined strings:
NSString *strurl = #"http://....";
As for your URL issue, Georg is right:
NSURL *jsonURL = [NSURL URLWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize%3Atrue%7CBarossa+Valley,SA%7CClare,SA%7CConnawarra,SA%7CMcLaren+Vale,SA&sensor=false"];
Fixed that issue for me.
However, the next bit:
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
Is deeply troubling. You should never do synchronous data reads on the main thread. initWithContentsOfURL is going to spawn a synchronous NSURLConnection to go fetch that data and might return sometime before sunday, but you never know. (This method is ok for filesystem loads, where things are much more deterministic)
Look into an asynchronous loading API like NSURLConnection from Apple, or better yet ASIHTTPRequest, about which there is ample documentation online.
Happy webservicing!
I think, the root of cause is your string creating method.
NSString *strurl = [[NSString alloc]initWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false"];
Try with ...
NSString *strurl = [[NSString alloc]initWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false"];
We are pulling content off our website using XML/NSMutableURLRequest and sometimes it pulls through the "curly" style apostrophe and quotes, ’ rather than '. NSMutableURLRequest seems to hate these and turns them into the strange \U00e2\U0080\U0099 string.
Is there something that I can to do prevent this? I am using the GET method, so should I be somehow telling it to use UTF-8? Or, am I missing something?
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
NSString *urlStr = [NSString stringWithFormat:#"%#",url];
NSURL *serviceUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setHTTPMethod:#"GET"];
NSURLResponse *serviceResponse;
NSError *serviceError;
app.networkActivityIndicatorVisible = NO;
return [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
NSURLConnection returns an NSData response. You can take that NSData response and turn it into a string. Then take this string, turn it back into a NSData object, properly UTF-8 encoding it along the way, and feed it to NSXMLParser.
Example: (Assuming response is the NSData response from your request)
// long variable names for descriptive purposes
NSString* xmlDataAsAString = [[[NSString alloc] initWithData:response] autorelease];
NSData* toFeedToXMLParser = [xmDataAsAString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser* parser = [[[NSXMLParser alloc] initWithData:toFeedToXMLParser] autorelease];
// now utilize parser...
I would suggest replacing those characters using stringByReplacingCharactersInRange:withString: to replace the unwanted strings.
NSString *currentTitle = #"Some string with a bunch of stuff in it.";
//Create a new range for each character.
NSRange rangeOfDash = [currentTitle rangeOfString:#"character to replace"];
NSString *location = (rangeOfDash.location != NSNotFound) ? [currentTitle substringToIndex:rangeOfDash.location] : nil;
if(location){
currentTitle = [[currentTitle stringByReplacingOccurrencesOfString:location withString:#""] mutableCopy];
}
I've done this in the past to handle the same problem you describe.
Try using the stringByReplacingPercentEscapesUsingEncoding:
I have some source code to get the file name of an url
for example:
http://www.google.com/a.pdf
I hope to get a.pdf
because the way to join 2 NSStrings I can get is 'appendString' which only for adding a string at right side, so I planned to check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop the checking, return string fdp.a , after that I change fdp.a to a.pdf
source codes are below
-(NSMutableString *) getSubStringAfterH : originalString:(NSString *)s0
{
NSInteger i,l;
l=[s0 length];
NSMutableString *h=[[NSMutableString alloc] init];
NSMutableString *ttt=[[NSMutableString alloc] init ];
for(i=l-1;i>=0;i--) //check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop
{
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
if([ttt isEqualToString:#"/"])
{
break;
}
else
{
[h appendString:ttt];
}
}
[ttt release];
NSMutableString *h1=[[[NSMutableString alloc] initWithFormat:#""] autorelease];
for (i=[h length]-1;i>=0;i--)
{
NSMutableString *t1=[[NSMutableString alloc] init ];
t1=[h substringWithRange:NSMakeRange(i, 1)];
[h1 appendString:t1];
[t1 release];
}
[h release];
return h1;
}
h1 can reuturn the coorect string a.pdf, but if it returns to the codes where it was called, after a while system reports
'double free
*** set a breakpoint in malloc_error_break to debug'
I checked a long time and foudn that if I removed the code
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
everything will be Ok (of course getSubStringAfterH can not returns the corrent result I expected.), no error reported.
I try to fix the bug a few hours, but still no clue.
Welcome any comment
Thanks
interdev
The following line does the job if url is a NSString:
NSString *filename = [url lastPathComponent];
If url is a NSURL, then the following does the job:
NSString *filename = [[url path] lastPathComponent];
Try this:
Edit: from blow comment
NSString *url = #"http://www.google.com/a.pdf";
NSArray *parts = [url componentsSeparatedByString:#"/"];
NSString *filename = [parts lastObject];
I think if you have already had the NSURL object, there is lastPathComponent method available from the iOS 4 onwards.
NSURL *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *filename = [url lastPathComponent];
Swift 3
Let's say that your url is http://www.google.com/a.pdf
let filename = url.lastPathComponent
\\filename = "a.pdf"
This is more error free and meant for getting the localized name in the URL.
NSString *localizedName = nil;
[url getResourceValue:&localizedName forKey:NSURLLocalizedNameKey error:NULL];
I haven't tried this yet, but it seems like you might be trying to do this the hard way. The iPhone libraries have the NSURL class, and I imagine that you could simply do:
NSString *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *path = [url path];
Definitely look for a built in function. The libraries have far more testing and will handle the edge cases better than anything you or I will write in an hour or two (generally speaking).
I've got an RSS parser method and I need to remove whitespace and other nonsense from my extracted html summary. I've got a NSMutableString type 'currentSummary'. When I call:
currentSummary = [currentSummary
stringByReplacingOccurrencesOfString:#"\n" withString:#""];
Xcode tells me "warning: assignment from distinct Objective-C type"
What's wrong with this?
If currentSummary is already a NSMutableString you shouldn't attempt to assign a regular NSString (the result of stringByReplacingOccurrencesOfString:withString:) to it.
Instead use the mutable equivalent replaceOccurrencesOfString:withString:options:range:, or add a call to mutableCopy before the assignment:
// Either
[currentSummary replaceOccurencesOfString:#"\n"
withString:#""
options:NULL
range:NSMakeRange(0, [receiver length])];
// Or
currentSummary = [[currentSummary stringByReplacingOccurrencesOfString:#"\n"
withString:#""]
mutableCopy];
This works great for nested elements as well of course:
*Edited*
// Get the JSON feed from site
myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL
URLWithString:#"http://yoursite.com/mobile_list.json"]
encoding:NSUTF8StringEncoding error:nil];
// Make the content something we can use in fast enumeration
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary * myParsedJson = [parser objectWithString:myRawJson error:NULL];
[myRawJson release];
allLetterContents = [myParsedJson objectForKey:#"nodes"];
// Create arrays just for the title and Nid items
self.contentTitleArray = [[NSMutableArray alloc]init];
for (NSMutableDictionary * key in myArr) {
NSDictionary *node = [key objectForKey:#"node"];
NSMutableString *savedContentTitle = [node objectForKey:#"title"];
// Add each Title and Nid to specific arrays
//[self.contentTitleArray addObject:contentTitle];
//change each item with & to &
[self.contentTitleArray addObject:[[savedContentTitle
stringByReplacingOccurrencesOfString:#"&"
withString:#"&"]
mutableCopy]];
}
The code below, as shown in the use-case above might be helpful.
[self.contentTitleArray addObject:[[contentTitle
stringByReplacingOccurrencesOfString:#"&"
withString:#"&"]
mutableCopy]];
That usually means you dropped the asterisks in the definition of (in this case) currentSummary.
So you most likely have:
NSMutableString currentSummary;
when you need:
NSMutableString *currentSummary;
In the first case, since Objective-C classes are defined in type structures, the complier thinks your trying to assign a NSString to a struct.
I make this typo on a distressingly regular basis.