Search code examples
iphoneobjective-ciosios6

NSData from NSString as it is


Hey i'm trying to get text to ASCII and then store it on a server then when i get it back i want to decode the text back to NSString

i've used the following code to test on a random app.. but in here i have NSdata as a global variable so it works fine..

Question is how do i get the value NSString i get back from the server in NSData variable so i can convert it back to the text i encoded from.

.h

@interface passTestViewController : UIViewController
{
    NSString *text;
    NSData *d;
}

.m

- (IBAction)eButton:(id)sender {
    text = [NSString stringWithFormat:@"%@%@%@",@"!",[_textField text],@"!"];

    d=[[NSString stringWithFormat:@"%@",text] dataUsingEncoding:NSASCIIStringEncoding];
    text = [NSString stringWithFormat:@"%@",d];

    [_label setText:text];
}

- (IBAction)dButton:(id)sender {

    NSString *dString = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];
    dString = [dString stringByReplacingOccurrencesOfString:@"!" withString:@""];
    [_label setText:dString];
}

i need to get it to NSData. i send it to my server thru JSON and then later when i get it back... i get it as a string.. what i need is

NSData *d = stringThatIGetBackFromJson; 

so i can convert it thru

NSString *dString = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];

to get the original string entered by user.

Also the string i get from this after encode has the signs and spaces.. '<' '>' and ' ' It wouldn't go thru to the url so what i did was remove the spaces and < > thru

myString = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];
myString = [myString stringByReplacingOccurrencesOfString:@"<" withString:@""];
myString = [myString stringByReplacingOccurrencesOfString:@">" withString:@""];

so now what i'll get back is gonna be just numbers like "40786d61646f6f2131323334216b6d646f616f"... is there anyway around this ? to compare i'm just checking encoding the text and following the same steps and then comparing if isEqualTo, but i would like to get the text back to be able to post on the app.


Solution

  • Try the below three ways to convert NSString to NSData

    1.NSData* data = [yourString dataUsingEncoding:NSUTF8StringEncoding];

    2.NSData* data=[yourString dataUsingEncoding: [NSString defaultCStringEncoding] ];

    3.NSData* data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
    data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];

    If the data is not null-terminated,

    NSString* myString = [[NSString alloc] initWithData:nsDataString
                                             encoding:NSUTF8StringEncoding] ;
    

    If the data is null-terminated

    NSString* myString = [NSString stringWithUTF8String:[nsDataString bytes]];