Hi Readers!
In this blog you can find both versions (Obj C & Swift) for converting NSData to NSString or vice-versa.
Objective C
NSString * str = @"Hello";
NSData * data =[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Data = %@",data);
NSString * convertedStr =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Converted String = %@",convertedStr);
Output:
Data = <48656c6c 6f>
Converted String = Hello
Swift
var str = "Hello"
var data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
println("Data = \(data)")
var convertedStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
println("Converted String = \(convertedStr)")
Output:
Data = Optional(<48656c6c 6f>)
Converted String = Optional(Hello)
0 Comment(s)