How do I convert an NSString value to NSData? - ios

How do I convert an NSString value to NSData?

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

NSString *str = #"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
you can take reference from this link

Do:
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
then feel free to proceed with NSJSONSerialization:JSONObjectWithData.
Correction to the answer regarding the NULL terminator
Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:
As documented by dataUsingEncoding::
Return Value
The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument
As documented by getCString:maxLength:encoding: and cStringUsingEncoding::
note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator

In case of Swift Developer coming here,
to convert from NSString / String to NSData
var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

Objective-C:
NSString *str = #"test string";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Swift:
let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String

First off, you should use dataUsingEncoding: instead of going through UTF8String. You only use UTF8String when you need a C string in that encoding.
Then, for UTF-16, just pass NSUnicodeStringEncoding instead of NSUTF8StringEncoding in your dataUsingEncoding: message.

For Swift 3, you will mostly be converting from String to Data.
let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)

NSString *str = #"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

Objective-C:
NSString to NSData:
NSString* str= #"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
Swift:
String to Data:
var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)
Data to String:
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!

Update Swift 5.x
let str = "teststring"
let data = str.data(using: .utf8)

Swift:
Swift 5.x
let myStringToConvert = "My String to Convert in Data"
let myData = myStringToConvert.data(using: .utf8)
String to Data:
var myStringToConvert = "My String to Convert in Data"
var myData = myStringToConvert.data(using: String.Encoding.utf8)
Data to String:
var backToMyString = String(data: myData!, encoding: String.Encoding.utf8) as String!
OBJECTIVE C:
NSString to NSData :
NSString* myStringToConvert= #"My String to Convert in Data";
NSData* myData=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSData to NSString :
NSString* backToMyString = [[NSString alloc] initWithData: myData encoding:NSUTF8StringEncoding];

NSString *str = #"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];

Objective-C
NSString *str = #"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
Swift
let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)

In Swift there is an API which returns a non-optional
let str = "teststring"
let data = Data(str.utf8)

Related

How to convert video file to Base64 string in IOS?

I want to convert local resource folder video file(12345.mp4) to base64 encoding string and then send into the server side from API but web team telling invalid base64 encoded string. Is this correct?
This is my code :
NSString *base64String = #"";
NSError *error;
NSData *videoData;
NSString *strVideoPath = [[NSBundle mainBundle] pathForResource:#"12345" ofType:#"mp4"];
videoData = [[NSData alloc]initWithContentsOfFile:strVideoPath options:NSDataReadingMappedIfSafe error:&error];
base64String = [videoData base64EncodedStringWithOptions:0];
In swift version you can convert video like this
*let tempURL = info[UIImagePickerController.InfoKey.mediaURL]
let data = NSData(contentsOf: tempURL as! URL)
print("\(String(describing: data?.length))")
if data?.length ?? 0 > 0{
guard data != nil else {
return
}
let base64String = data!.base64EncodedString(options: .lineLength64Characters)
self.video = base64String
}*

Convert string into url

I am getting something when I convert string to NSURL.
My code id...
NSString *urlString = [[NSString alloc]initWithFormat:#"http://host name/index.php?id=%#&mob=%#&name=%#&mail=%#&m=23", self.deviceId, self.pnumber, self.name, self.email];
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *urlPattern = [NSURL URLWithString:urlString];
NSLog(#"%#", urlPattern);
http://host name/index.php?dev_id=73EA1D1D-E6E3-485C-883D-DF952E116&mob=%3CUITextField:%200x7fe247063c00;%20frame%20=%20(0%20128.333;%20310.667%2040.6667);%20text%20=%20'';%20opaque%20=%20NO;%20autoresize%20=%20RM+BM;%20gestureRecognizers%20=%20%3CNSArray:%200x608000244c50%3E;%20layer%20=%20%3CCALayer:%200x60800003eee0%3E%3E&name=%3CUITextField:%200x7fe247055800;%20frame%20=%20(0%2044;%20310.667%2040.3333);%20text%20=%20'';%20opaque%20=%20NO;%20autoresize%20=%20RM+BM;%20gestureRecognizers%20=%20%3CNSArray:%200x608000244410%3E;%20layer%20=%20%3CCALayer:%200x60800003e240%3E%3E&mail=%3CUITextField:%200x7fe24601ae00;%20frame%20=%20(0%20213;%20310.667%2040.3333);%20text%20=%20'';%20opaque%20=%20NO;%20autoresize%20=%20RM+BM;%20gestureRecognizers%20=%20%3CNSArray:%200x608000243c90%3E;%20layer%20=%20%3CCALayer:%200x60c000038580%3E%3E&m=23
How to convert string to NSURL
Probably you are assigning textfield to urlString. Check for self.pnumber whether its a textfield or string. If textField then set as self.pnumber.text and similarly check for all data.
change self.pnumber, self.name, self.email to self.pnumber.text, self.name.text, self.email.text
use like
NSString *urlString = [[NSString alloc]initWithFormat:#"http://host name/index.php?id=%#&mob=%#&name=%#&mail=%#&m=23", self.deviceId, self.pnumber.text, self.name.text, self.email.text];
Try This
let NSHipster = URL(string: "http://nshipster.com/") //returns a valid URL
let invalidURL = URL(string: "www.example.com/This is a sentence") //Returns nil
for more detail:
http://www.codingexplorer.com/creating-and-modifying-nsurl-in-swift/

Sending parameter to webservice

I need to send french string "Commentaire d’arret" to webservice in objective c.
But my app crashes when I am sending this string as parameter to service. And normal string like "india" is working fine.
Can any one help me.
Encode your parameter for a GET request:
let param = "Commentaire d’arret"
let encodedParam = (param as NSString).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Results in Commentaire%20d%E2%80%99arret.
If you want to send a POST request prepare your post body like this:
let postString = "param=consultés"
let postData = postString.data(using: .utf8)
Objective-C
NSString *param = #"Commentaire d’arret";
NSString *encodedParam = [param stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString *postString = #"param=consultés";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
As you said I have checked your code and you need to do encoding before converting to your URL. try this.
NSString *searchApi = [NSString stringWithFormat:#"xxx/xxx/index?
q=#consultés"];
searchApi = [searchApi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *tempURL = [NSURL URLWithString:searchApi];
Try this:
NSString *strParam = #"Commentaire d’arret";
NSString *encodedParam = [strParam stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

How can I use NSJSONSerialization with special characters like "ñ"?

I'm using NSJSONSerialization to parse Google suggestions.
The query "f" returns these suggestions:
["f",["facebook","flipkart","fox news","forever 21","friv","fandango","fedex","fitbit","food near me","flights"]]
The parser works fine but when there are special characters like "ñ" for the query "fac":
["fac",["facebook","facebook search","fac","facebook app","facebook lite","facebook login","facebook logo","facebook messenger","facetime","facebook en español"]]
It throws an exception:
Error Domain=NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 139." UserInfo={NSDebugDescription=Unable to convert data to string around character 139.}
Any ideas? I tried all different reading options but none of them works.
#pragma mark -
- (void)request:(NSString *)text
{
NSMutableArray *items = [[NSMutableArray alloc] init];
NSString *query = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString *languageCode = [[NSLocale preferredLanguages] firstObject];
if (!languageCode) {
languageCode = #"en";
}
NSString *URLString = [NSString stringWithFormat:#"http://suggestqueries.google.com/complete/search?q=%#&client=firefox&hl=%#", query, languageCode];
NSError *downloadError = nil;
NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString] options:0 error:&downloadError];
if (!downloadError && JSONData) {
NSError *parseError = nil;
id object = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&parseError];
if (!parseError && object) {
if ([object isKindOfClass:[NSArray class]]) {
NSArray *objects = (NSArray *)object;
NSArray *texts = [objects objectAtIndex:1];
for (NSString *text in texts) {
SNGoogleItem *item = [[SNGoogleItem alloc] initWithText:text];
[items addObject:item];
}
[_delegate google:self didRespondWithItems:items];
}
else {
[_delegate google:self didRespondWithItems:items];
}
}
else {
[_delegate google:self didRespondWithItems:items];
}
}
else {
[_delegate google:self didRespondWithItems:items];
}
}
JSONSerialization supports all the encodings in JSON spec, says Apple documentation.
You didn't provide much info about the encoding scheme of your data but I guess you use nonLossyASCII or something like that, which is not supported by JSONSerialization.
Here is how I convert data to/from JSON:
let rawString = "[[\"facebook en español\"]]"
// if I use String.Encoding.nonLossyASCII below, I get the error you are getting
let data = rawString.data(using: String.Encoding.utf8)
let dict = try! JSONSerialization.jsonObject(with: data!)
let convertedData = try! JSONSerialization.data(withJSONObject: dict)
let convertedString = String(data: convertedData, encoding: String.Encoding.utf8)!
// now convertedString contains "ñ" character
This will convert whatever encoding used to UTF8:
NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString] options:0 error:&downloadError];
NSString *convertedJSONString; BOOL usedLossyConversion;
[NSString stringEncodingForData:JSONData encodingOptions:0 convertedString:&convertedJSONString usedLossyConversion:&usedLossyConversion];
NSData *convertedJSONData = [convertedJSONString dataUsingEncoding:NSUTF8StringEncoding];
Now, it works!

NSJSONSerialization is changing the date separator from yyyy/MM/dd to yyyy\/MM\/dd [duplicate]

This question already has answers here:
how to prevent NSJSONSerialization from adding extra escapes in URL
(5 answers)
Closed 6 years ago.
NSString *date = [userDefaults objectForKey:KEY_FORM7_DECLARATION_DATE];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:date, #"DATE",nil]
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
When I do NSLog(#"%#", date) It shows me 2016/10/30
But When I try to print NSLog(#"%#", result) the date changes to 2016\/10\/30. Any help would be appreciated.
Seems like it's intended behaviour of NSJSONSerialization: similar question
For your simple case I can only come up with simple workaround: serialize the JSON with substitution sign and then use serialized string as a format:
let dateString = "2016/10/30"
var dict = ["DATE": "%#"]
do {
let data = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
let format = String(data: data, encoding: NSUTF8StringEncoding)!
let result = String(format: format, dateString)
} catch {
print(error)
}

Resources