How to Convert an Nsstring Value to Nsdata

is it possible to Convert NSString to NSData?

There are two ways to convert Data to String and vice versa.

– If data represents a readable string use NSString's initWithData:encoding: and dataUsingEncoding:. The encoding value of both must match.

– If data represents raw data (for example an image) use NSData's base64EncodedStringWithOptions: and initWithBase64EncodedString:options:.

But never use NSString's initWithFormat and pass an NSData object. That's pointless.

On conversion from NSString to NSData

No.

+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length

This method takes simply 2 parameters: void pointer to byte stream in memory and length in the terms how many should be taken into NSData object from this byte stream. This method, as any other, doesn't have a clue and doesn't care, how you got this byte stream and certainly doesn't know anything about UTF8String, it cares only about data types, that they match method signature.

Your idea about how to determine the length of the string is also wrong as Matthias explained. Use strlen C function for that. This function checks upon string termination null character \0.

Convert Large NSString to NSData in Notification Service Class

I am going to answer here, it can help some one else in future.

The main problem it wasn’t the method, in debug the information was coming correctly in body parameter of push notification but when I was trying to getting the body like :

NSString* body = self.bestAttemptContent.body;

The main problem is here, when the string body is long size, it cut automatically and I didn’t find any documentation about it... however I added “data” parameter in payload of push notification and when I receive the push notification I get the string from data parameter and it gives correctly all the string.

How to convert NSString back to NSData after converting NSData to NSString?

You need to decode the base-64 encoded string, with something like:

NSData *data = [[NSData alloc] initWithBase64EncodedString:str
options:0];

Where str is the string read from the database.

Converting NSString to NSData and vice versa

NSString to NSData:

NSString* str= @"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

NSData to NSString:

NSString* newStr = [[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding];

Creating NSData from NSString in Swift

In Swift 3

let data = string.data(using: .utf8)

In Swift 2 (or if you already have a NSString instance)

let data = string.dataUsingEncoding(NSUTF8StringEncoding)

In Swift 1 (or if you have a swift String):

let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)

Also note that data is an Optional (since the conversion might fail), so you'll need to unwrap it before using it, for instance:

if let d = data {
println(d)
}


Related Topics



Leave a reply



Submit