0

The following code works perfectly to convert the NSData that I got from a URL/JSON file to a NSString, EXCEPTION MADE by the cases that data contains line breaks!

What's wrong with my code?

My Code:

NSError  *errorColetar = nil;
NSURL    *aColetarUrl = [[NSURL alloc]initWithString:@"http://marcosdegni.com.br/petsistema/teste/aColetar3.php"];
NSString *aColetarString = [NSString stringWithContentsOfURL:aColetarUrl encoding:NSUTF8StringEncoding error:&errorColetar];

NSLog(@"NSString: %@", aColetarString);

if (!errorColetar) {
    NSData *aColetarData = [aColetarString dataUsingEncoding:NSUTF8StringEncoding];
    self.arrayAColetar = [NSJSONSerialization JSONObjectWithData:aColetarData options:kNilOptions error:nil];
}
NSLog(@"arrayAColetar %@", self.arrayAColetar);

Log Results:

**NSString**: [{"id_atendimento":"2","observacoes":"ABC-Enter-->
DEF-Enter-->
GFH-END"},{"id_atendimento":"1","observacoes":"123Enter-->
345Enter-->
678End"}]

**arrayAColetar** (null)

As you can see my bottom line is an empty array :(

Thanks in advance!

1 Answers1

0

By checking the error message hidden under 'error:nil' I found a "Unescaped control character around character" issue and implemented the code below from Unescaped control characters in NSJSONSerialization and got a new 'cleaned' string.

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString { 

NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet]; 
NSRange range = [inputString rangeOfCharacterFromSet:controlChars]; 
if (range.location != NSNotFound) { 
    NSMutableString *mutable = [NSMutableString stringWithString:inputString]; 
    while (range.location != NSNotFound) { 
        [mutable deleteCharactersInRange:range]; 
        range = [mutable rangeOfCharacterFromSet:controlChars]; 
    } 
    return mutable; 
} 
return inputString; 

}

Community
  • 1
  • 1