I'm trying to create base64 data for protobuf encoding library.
I found this code:
/* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options.
*/
#availability(iOS, introduced=7.0)
func base64EncodedDataWithOptions(options: NSDataBase64EncodingOptions) -> NSData
In the source code of NSData. As I got, this method have to return base64encoded NSDate.
But I can't understand, how to convert my NSData(which I'm receiving from API) to this Base64 NSDate.
You said your data is NSData. Then just call the base64EncodedDataWithOptions and assign it to a new variable/constant:
let newData = yourData.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.allZeros)
Check NSDataBase64EncodingOptions for encoding options and change allZeros as appropriate.
Related
I have a large piece of NSData I want to send to my server, but I also want to send a string dictionary of string keys mapped to string keys.
How do I POST both in the same request?
Almost all guides show wrapping it in an NSDictionary then using NSJSONSerialization to turn it into NSData then POST that, but I can't have NSData and NSStrings in the same NSDictionary it just crashes, so I assume I have to keep it separate, but how would that look?
Essentially how do I serialize JSON into NSData and then also have a separate NSData blob with it?
let body = NSMutableDictionary()
body.setValue("myString" forKey: "stringType")
body.setValue(data?.base64EncodedString(options: .lineLength64Characters) forKey: "dataType")
In this way you can have both data and string in the dictionary.
Here 'data?.base64EncodedString(options: .lineLength64Characters)' returns you a string with base64 encoding. So your dictionary contains only string and at server end you have to covert it back to data.
Hope it solves your issue
I use gzip library to convert data to gzip data
If I want to get string from data I do String(data: data, encoding: .utf8) . But if I do the same for gzip data I get nil string, because as far as I understand it's impossible to convert gzip data to string with .utf8 encoding.
I need that because I want to compare data with a server developer (because he sometimes he says that my data is incorrect format, but sometimes it's ok, and that's strange because I use the same library, and I have thoughts that may be the problem is on server side).
Is there any way to convert gzip data to any string to compare it then later?
If this is just for debug purpose, then I think the quickest way is:
let myGZipNSData = myGZipData as! NSData //I wrote a "!" just for the sample)
print("myGZipNSData: \(myGZipNSData)")
It should output:
myGZipNSData: <5b226d79 41727261 7956616c 75653022 2c226d79 41727261 7956616c 75653122 5d>
This relies on -description method of NSData which print "<hexValue>".
Do not rely on it on release version, almost never rely on -description (yes, Apple could change the behavior of -description in next release. It happened on a different class).
Other way (safer) to get almost the same result, you can check this question: How to convert Data to hex string in swift which you get you the same result (almost, less space, and no </>) as the previous one.
Other way: Base 64
Use base64EncodedString() method of Data:
let base64Str = myGZipData?.base64EncodedString()
print("base64Str: \(base64Str!)")
Output:
base64Str: WyJteUFycmF5VmFsdWUwIiwibXlBcnJheVZhbHVlMSJd
Now, there should be other way:
Have a array representation with Int values (between 0/255 instead of hex), but it seems to be for debug purpose so check if you can "reproduce the current solutions" (working/fast implementation) I gave you, and check with the server developer what he/she can do on his/her side too to compare.
Note:
For the purpose of this sample, myGZipData is constructed this way:
let array = ["myArrayValue0", "myArrayValue1"]
let myGZipData = try? JSONSerialization.data(withJSONObject: array, options:[])
It's not really a GZipData, but the goal was to quickly have a Data object "big enough".
I have the following code to turn NSUserDefaults into NSData and then send it with an instance of MFMailComposeViewController:
let defaultsData = NSKeyedArchiver.archivedDataWithRootObject(NSUserDefaults.standardUserDefaults().dictionaryRepresentation())
mailViewController.addAttachmentData(defaultsData, mimeType: "text/txt", fileName: "details.txt")
Pretty simple stuff, but when I send it off I get a .txt that is very garbled where it starts with this:
bplist00‘������òôX$versionX$objectsY$archiverT$top�܆Ø|���ô�ö�õ�ú�ù�û�ü�†�°�¢�£�§�•�¶�ß�®�©�™�´�¨�≠�Æ�Ø�∞�±�≤�≥�¥�µ�∂�∑�∏�π�∫�ª�º�Ω�æ�ø�¿�¡�¬�√�ƒ�≈�∆�«�»�…� �À�Ã�Õ�Œ�œ�–�—�“�”�‘�’�÷�◊�ÿ�Ÿ�⁄�€�‹�›�fi�fl�‡�Ï�Ì�Ó�Ô��Ò�Ú�Û�Ù�˙�˚�¸"#$)*+./367?#ABCDGJVWcfqrstuvwxy|∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·Ìıˆ˜˙¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ�
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxy|ÇÉÜáäçéëíóU$null”� �
���R�òWNS.keysZNS.objectsV$classØE�
�������������������
What am I doing wrong?
This is indeed expected. The resulting NSData of NSKeyedArchiver is binary property list (bplist) representation of the dictionary. So you get binary data. What did you expect to receive?
I'm trying to download a PDF and display it in a UIWebView. The API is giving me the PDF as a String, looking like this:
I convert the string to NSData:
self.fileData = responseObject!.dataUsingEncoding(NSUTF8StringEncoding)!
Then i load it into my WebView, however i am getting:
failed to find PDF header: `%PDF' not found.
What am i doing wrong?
You could save the string as a file, with String's writetoFile method for example, then grab this file directly from the webview with UIWebView's loadRequest method.
Note that usually a PDF encoded as a String should be encoded as Base64 String. If this is the case for your String, then you could use NSData's base64EncodedString initializer to read the string content as data.
I want to implement a web service to recover an array of my entity PictureCaptures :
PictureCaptures
---------------
- description : string
- captureDate : DateTime
- photoBinary : byte[]
The web service will be mainly called by an iOS application.
What's the best way to implement it, because of the byte array attribute?
Am I suppose to return the byte array without any transformation, as a simple JSON attribute? If yes, how to interpet the JSON response ? -In this case JSONObjectWithData:options:error: doesn't work, too much data and memory issue)-
Thank you for your help.
I would suggest you add two resources: one for the meta data (description, captureDate and so on) and one for the binary data. Let the meta data resource contain a link to the binary photo data.
Like this:
GET /images/1234
Response:
{
description: "Nice photo",
captureDate: "2012-04-23T18:25:43.511Z",
photoData: "http://example.org/images/1234/photo"
}
and http://example.org/images/1234/photo returns the raw photo data
(see also See also The "right" JSON date format for a discussion on date formats).
when you get JSON responce you shoud convert the btye array to NSData.
first add Base64.h and m file to the project ( you can find it easily on internet)
then import Base64.h
from your JSON data
NSString *data= [yourJSONDict objectForKey:#"photoBinary"];
NSData* imageData = [data base64DecodedData];
UIImage *imag=[UIImage imageWithData:imageData];
[yourImageView setImage:imag];
this might help you.