Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to convert NSData to NSString or vice versa in Objective C and Swift

    • 0
    • 4
    • 2
    • 1
    • 0
    • 0
    • 0
    • 0
    • 25.3k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: