如何将包含换行符的NSData转换为NSString

时间:2014-12-01 16:45:07

标签: ios7

以下代码可以很好地将我从URL / JSON文件获取的NSData转换为NSString, EXCEPTION MADE ,因为数据包含换行符

我的代码出了什么问题?

我的代码:

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);

记录结果:

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

**arrayAColetar** (null)

正如您所看到的,我的底线是一个空数组:(

提前致谢!

1 个答案:

答案 0 :(得分:0)

通过检查隐藏在'错误:nil'之下的错误消息我找到了一个"未转义的控制角色围绕着角色"从Unescaped control characters in NSJSONSerialization发出并实施以下代码 得到一个新的'清洁'字符串。

- (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; 

}