AFNetworking crashing in multilingual app - ios

Ride[source_name]=2152,%20Mohali%20Stadium%20Rd,%20Phase%2010,%20Sector%2064,%20Sahibzada%20Ajit%20Singh%20Nagar,%20Punjab%20160062,%20भारत
This parameter is causing crash while running in Hindi while working fine with Spanish and English. Please suggest me on it. Crash description is as following:-
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not
satisfying: URLString'

Check with this
Objective - C
NSString *string = #"भारत";
NSString *encoded = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
Swift 3.0
let string = "भारत"
let urlString = string.addingPercentEncoding( withAllowedCharacters: . urlUserAllowed)
Output :: %E0%A4%AD%E0%A4%BE%E0%A4%B0%E0%A4%A4

Add below line of code to avoid invalid parameters in url.
NSString *str = ...; // Your URL
NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet];
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
Deprecated Code Before ios 9.0 :
NSString *str = ...; // Your URL
NSString *urlAsString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Related

ios crash in 'NSCFString dataUsingEncoding:allowLossyConversion:]: didn't convert all characters'

I want to convert NSString to NSData with following code:
NSUInteger lengthTest = contentStr.length;
NSStringEncoding encodingStr = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
if ([contentStr canBeConvertedToEncoding:encodingStr]) {
NSData *data = [contentStr dataUsingEncoding:encodingStr allowLossyConversion:YES];
lengthTest = [data length];
}
But my fabric report a Crash named: NSCFString dataUsingEncoding:allowLossyConversion:]: didn't convert all characters'
I want to know which character could cause this problem and fix it , expecting someone could help me.

Extracting URLs from NSString into NSMutableString

I have a file with the following content:
cool name http://myurl1.tld/subdir/dir/var/ awesome\nanother cool name http://sub.domain.tld/dir/ nice\nsome nice name http://myname.tld/var/folder/ some\n
I read the file with this Objetive-C code:
NSData* data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:#"../files/name.ext"]];
NSString* raw = [[NSString alloc]
initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
To extract all URLs from the above sample I use:
NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:raw options:0 range:NSMakeRange(0, [raw length])];
My goal is to append all extracted URLs into one single string and separate them with a semicolon (without any other stuff from the file) with this loop:
NSMutableString *allURLStrings = [NSMutableString string];
for (NSString *s in matches) {
[allURLStrings appendString:s];
[allURLStrings appendString:#";"];
}
Whenever I try to run the code I get the following output:
terminating with uncaught exception of type NSException (lldb)
I tried to use the loop like this, but then the substringForCurrMatch only contains a slash (/):
NSMutableString * allRepoString = [NSMutableString string];
for (NSTextCheckingResult *s in matches) {
NSString* substringForCurrMatch = [s.URL path];
[allRepoString appendString:substringForCurrMatch];
[allRepoString appendString:#";"];
}
When I inspect s in the loop it shows me the correct object:
Is there a way to get this code working?
EDIT complete error message:
2016-08-11 23:00:19.272 AppName[34831:2892247] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[fetchurlsource allURLStrings]: unrecognized selector sent to instance 0x14c55ea00'
*** First throw call stack:
(0x181fa2db0 0x181607f80 0x181fa9c4c 0x181fa6bec 0x181ea4c5c 0x1000e8b6c 0x1000e8ee0 0x187100c40 0x187100844 0x18710759c 0x187104a88 0x18717afa4 0x1873a63ac 0x1873aa5f0 0x1873a7764 0x1839437ac 0x183943618 0x1839439c8 0x181f5909c 0x181f58b30 0x181f56830 0x181e80c50 0x18716f94c 0x18716a088 0x1000edb10 0x181a1e8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
None of the code you posted so far can result in the exception you posted.
But the following code is incorrect:
NSMutableString * allRepoString = [NSMutableString string];
for (NSTextCheckingResult *s in matches) {
NSString* substringForCurrMatch = [s.URL path];
[allRepoString appendString:substringForCurrMatch];
[allRepoString appendString:#";"];
}
You do not want to call the path method on s.URL. To get the full URL as a string, use absoluteString. This will give you the URL as a string. path just gives you the path portion of the URL.
NSMutableString * allRepoString = [NSMutableString string];
for (NSTextCheckingResult *s in matches) {
NSString* substringForCurrMatch = [s.URL absoluteString];
[allRepoString appendString:substringForCurrMatch];
[allRepoString appendString:#";"];
}

String encode in objective c

I am very new to Objective-C.
I want to get the encoded content for a NSString. In java I can do that as follows,
String str = "https://www.google.co.in/#q=ios+sqlite+crud+example";
String encodedParam = URLEncoder.encode(str, "UTF-8");
I am using http://www.tutorialspoint.com/compile_objective-c_online.php to test the codes posted in stackoverflow. There is no solution yet. I know its trivial one. Struggling to find a way though.
tried with following function, and it says following error while compile,
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
Error,
sh-4.3$ gcc `gnustep-config --objc-flags` -L/usr/GNUstep/System/Library/Libraries -lgnustep-base -lobjc *.m -o main
main.m: In function 'main':
main.m:7:14: error: 'urlEncodeUsingEncoding' undeclared (first use in this function)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
^
main.m:7:14: note: each undeclared identifier is reported only once for each function it appears in
main.m:7:36: error: expected ';' before ':' token
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
Edit as per the answers,
Suggested by Patrick, I used the code as follows,
NSString *storedURL = #"google.com/?search&q=this";
NSString *urlstring = [NSString stringWithFormat:#"http://%#/",storedURL];
NSURL *url = [NSURL URLWithString:urlstring];
NSError *error = nil;
NSStringEncoding encoding;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
NSLog (my_string);
Nothing printed in console... Is it my NSLog is right?
Suggested by lightwolf, my code is looks like below,
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSString *encodedParam = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog (encodedParam);
it prints the log, but value is same as the str..... not encoded... I want this str as
https%3A%2F%2Fwww.google.co.in%2F%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
If you want to encode a specific range of characters you chould use
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSString *encodedParam = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSLog (#"%#", encodedParam);
Note the invertedSet; In that way, you are encoding all characters except the set specified (all alphanumeric ones)
The result is
https%3A%2F%2Fwww%2Egoogle%2Eco%2Ein%2F%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
If you want to use a specific set of characters you should use
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSCharacterSet* set = [NSCharacterSet characterSetWithCharactersInString:#"!*'();#&=+$,?%#[]"];
NSString *encodedParam = [str stringByAddingPercentEncodingWithAllowedCharacters:[set invertedSet]];
NSLog (#"%#", encodedParam);
In this case I intentionally missed / and : so the result is
https://www.google.co.in/%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
Maybe this is what you want
NSString *str = #"<html><head><title>First</title></head><body><p>Parsed HTML into a doc.</p></body></html>";
NSString *encodedParam = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You have to encode only the params, not the entire URL of course

Special Character to Original string - Objective C

I have tried the string(contain special character) to original String. The string received from service. I tried many codes. But i cant get the original String.
i tried the following code
// \U00e0\U00ae\U0089\U00e0\U00ae\U00b2\U00e0\U00ae\U0095\U00e0\U00ae\U00ae\U00e0\U00af\U008d
NSString *name2escaped = #"\\U00e0\\U00ae\\U0089\\U00e0\\U00ae\\U00b2\\U00e0\\U00ae\\U0095\\U00e0\\U00ae\\U00ae\\U00e0\\U00af\\U008d";
NSString *name2 = [NSString stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"name2 = %#", name2);
inputvalue.stringValue = name2;
NSLog (#"%#",name2);
Output prints: à®à®²à®à®®à¯
I worked in Mac OS X development 10.9 Mavericks
Service sometimes send chinese character also. Can anybody help me
As according to your requirement output should be Tamil or Chinese or English Language
Change NSNonLossyASCIIStringEncoding to NSUTF16StringEncoding :
NSString *name2escaped = #"\\U00e0\\U00ae\\U0089\\U00e0\\U00ae\\U00b2\\U00e0\\U00ae\\U0095\\U00e0\\U00ae\\U00ae\\U00e0\\U00af\\U008d";
NSString *name2 = [NSString stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSUTF16StringEncoding];
NSLog(#"name2 = %#", name2);
Output is : name2 = 屵〰攰屵〰慥屵〰㠹屵〰攰屵〰慥屵〰戲屵〰攰屵〰慥屵〰㤵屵〰攰屵〰慥屵〰慥屵〰攰屵〰慦屵〰㡤 –
I did it
My code is
- (NSString *) OrigninalString:(NSString *)getfilername
{
const char *c;
NSString *name2escaped = [NSString stringWithFormat:#"%#",getfilername];
NSString *string = [NSString
stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
c = [string cStringUsingEncoding:NSISOLatin1StringEncoding];
if (!c) {
c = [name2escaped cStringUsingEncoding:NSISOLatin1StringEncoding];
}
NSString *newString = [NSString stringWithCString:c encoding:NSUTF8StringEncoding];
c = nil;
string = nil;
return newString;
}

How to fix this mutating error?

I'm getting this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with replaceCharactersInRange:withString:'
But I can't figure out what immutable object I'm mutating.
NSRange subRange = [self.label.text rangeOfString: #"="];
int numA = 5;
int numB = 3;
NSMutableString *mixed = [NSString stringWithFormat: #"%i %i", numA, numB];
NSMutableString *string = [NSString stringWithString: self.label.text];
subRange = [string rangeOfString: #"="];
if (subRange.location != NSNotFound)
[string replaceCharactersInRange:subRange withString:mixed];
Your NSMutableString creation calls aren't balanced properly. You're promising the compiler that you're creating a NSMutableString but you ask an NSString to create an instance.
For example:
NSMutableString *mixed = [NSString stringWithFormat: #"%i %i", numA, numB];
needs to be:
NSMutableString *mixed = [NSMutableString stringWithFormat: #"%i %i", numA, numB];
Your NSMutableStrings are actually instances of NSString. This is runtime detail, though there should at least be a warning for those lines. Change to:
NSMutableString *string = [self.label.text mutableCopy];
You need to create a NSMutableString like this:
[NSMutableString stringWithString: self.label.text];

Resources