REST web service to recover an array of pictures - ios

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.

Related

NSArray to NSData encoding formatting

I am putting together a program that reads the sensors within a cell phone and saves the sensor data to a core-data SQLite model, with each set of readings pertaining to a particular session
The program provides the user with the option to email a .csv file of a particular session.
Having never done this before, I approached the issue by initializing a delegate and context, and searching the core data for entities that pertain to a specified session. The entities that satisfy the session attribute then have their data fields (gps, mag, accel, gyro) read and put into a string. Then the string is appended to an array. All done in swift.
After the entities are searched and the array is created, I attempt to create a csv file for attachment to an email. The file is attached successfully, but my encoding technique is presenting additional data prepended and appended to the file.
I want to save a file on the phone and email a copy to the user.
Here is what I have to change the Array to NSArray before converting again to NSData:
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let path = paths[0].stringByAppendingPathComponent("SessionData.csv")
if !NSFileManager.defaultManager().fileExistsAtPath(path)
{
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
}
else
{
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
}
var handle: NSFileHandle = NSFileHandle(forWritingAtPath: path)
handle.truncateFileAtOffset(handle.seekToEndOfFile())
var arrayToWriteNS = (arrayToWrite as NSArray)
var dataNS: NSData = NSKeyedArchiver.archivedDataWithRootObject(arrayToWrite as NSArray)
handle.writeData(dataNS)
mc.setSubject(emailTitle)
mc.addAttachmentData(dataNS, mimeType: "text/csv", fileName: "SessionData.csv")
Here is the prepended and appended data:
bplist00‘()T$topX$objectsX$versionY$archiver—TrootĨ
!U$null“
V$classZNS.objectsÄ©ÄÄÄÄÄÄÄÄ Ä
"My Data"
“"#$'X$classesZ$classname¢%&WNSArrayXNSObjectWNSArray܆_NSKeyedArchiver(25:<IOT[fhrtvxz|~ÄÇÑ·Ø}KÁµÉQV_jmu~Üã*ù
In a large data session with 28,000 entities there may be ~750 lines of prepended data.
Any help that you can provide would be appreciated.
I'm new to iOS, Obj-C, and swift, thus I'm positive there is a better way to do this, I just haven't discovered a better method yet.
Thank you.
UPDATE: Ended up just using the NSString data encoding and writing to my file in increments:
handle.truncateFileAtOffset(handle.seekToEndOfFile())
var stringToWriteNS = (stringToWrite as NSString).dataUsingEncoding(NSUTF8StringEncoding)
handle.writeData(stringToWriteNS!)
You do not want NSKeyedArchiver, it is for archiving and restoring classes.
You need to go through the array and create a text representation of each item in a format you what to present to the user.
A quick search of CocoaPods reveals several projects that may fit you needs to generate csv format data.
This one might be what you need.
csv is fairly simple so it would be reasonable to format your data to csv by writing your own code.

iOS RestKit 0.2 What is the best way to parse local Json

I wave read many articles about parsing a json via an Http request but almost none answers the question about what is the most straight forward way to parse o local json string. I found some deferent solutions here Deserializing local NSString of JSON into objects via RestKit (no network download) some of them work some others don't. Is there any "official" RestKit support for local JSON string deserialization?
Fortunately Apple provides "NSJSONSerialization" class from iOS 5.0. to serialise your data.
Step 1 : convert your local JSON string to "NSData"
NSString *strLocalJSON = #"{data= "some data"}"; //just for ex. may not be valid one
NSData *dataJSON = [str dataUsingEncoding:NSUTF8StringEncoding];
Step2:
id jsonobject= [NSJSONSerialization JSONObjectWithData:dataJSON options:NSJSONReadingMutableContainers error:nil]; // resulting object may contain Dictionary or Array depends on your localjson
for further info refer https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
If your JSON is in a file then you use a file:// NSURL when you create your RestKit object manager. Everything else works as normal.
If the JSON is already in code, then you should save it to a file, or why are you needing to do any mapping? Anyway, you could use a combination of NSJSONSerialization and RKMappingOperation.

iOS NSJSONSerialization of JPG image encoded binary data from mongodb

I think I need some assistance in figuring out the correct NSJSONSerialization option to make my problem go away.
On my app I allow the user to select an image from the gallery - the image undergoes the following:
NSData *imageData = UIImageJPEGRepresentation(self.profileImageView.image, 0.0);
then
NSString *stringOfImageData = [imageData base64EncodedStringWithOptions:0];
before it is serialized like this:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict
options:NSJSONWritingPrettyPrinted
error:&error];
and then sent to my REST API. I then decode it in python using base64 like so:
profileImageData = base64.b64decode(request.json['image'])
It is then loaded in GridFS (mongodb). On extracting the data to send back to the app I first encode in base to base64 before using dumps() to send it back:
dumps(base64.b64encode(fs.get_last_version(request.json['userID']).read()))
Within iOS after receiving the data it goes through the below de-serialization:
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error]
I have narrowed by problem to the last NSJSONSerialization command. After the data is received by the app it is able to print to screen. After the Serialization I get a 'nil' :(
The Serialization and De-Serialization has been working great for strings, integers etc - it just doesn't work when I'm trying to move image data.
Thanks
EDIT: I am able to run a curl request against the API and then using an online base64 to image converter I can see my image. So it definitely means the issues is with the iOS side of decoding a json encoded base64 string.
EDIT: When I repeatedly run the deserialization - every 20th time or so the data is correctly converted. I think the solution might have to be to break up the data coming in.
EDIT: Error:
parsed error:Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unterminated string around character 17.) UserInfo=0x109c08790 {NSDebugDescription=Unterminated string around character 17.}
What you don't say is how you are receiving the data. My guess is you are trying to decode the data before you receive all of it, but since I don't know how it's a guess.
To better understand what's going on, try logging the size and hash of the data, to see if the length varies. You can also save each received data object to the file system - put them in the Documents folder and you can access them from your Mac. If the size never varies you will then have to compare a good data object to a bad one.
In fact you can write a little code to save an image as data and a base64 string, upload it, then pull it back, and save it. Now compare the data and strings. Once you find a difference, then look at. What is its offset from the start? How is it different?
When you understand this all you will be able to fix it.

Having trouble saving image to entity field on IOS

On my server I have a table that I want to get over to IOS sqllite table.
My server table has a field called data which is of type Image. The way I populated the field is that I wrote a C# app that converts an image to byte array and then write this byte array to sql Image column.
In IOS, I make a soap request to my wcf service and get all data from my table. I made sure data is received. My problem is writing received image data to my entity's binary data field. I use the following code for that.
NSString *key = (NSString *) [keys objectAtIndex:i]; // I made sure key is valid
NSData *data = (NSData *) [rowData GetValue:key]; // I made sure data is retrieved
[tblRow setValue:data forKey:key]; // After calling this, data for the key is nil.
Portion of Image Data Content
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAMdA2oDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDn7DRkuEtmmnETXUqww5UkM7dF4HGffAq/L4QC3VzaRyGW6tmjWeNUY7C4JXJAxyFP074qx4aa11nTbGKS5jjjYyBFLAOzNEygqO7KWDf8Brobi3ggWWS91aCG4ZIbi6mJ2vuWSYtIF6hS06qvptA9KmxVzh5fBt3dfuHbCBvmCnqQfu/yH403UPCGoTQeWbYSxbvLOMAJ2/Ou2i00K9jbyWlqv2SKSMNbRY3Myoqy4P8AECpOfpzxVWfS/
I am not the one writing the WCF Service that sends me the image data and I learned that the service applies base 64 encoding to the data and setting base 64 string to NSData object and trying to save it was failing. Once I decoded the data, everything worked fine.

sending images to server via json

I am posting data to a server from my ipad using json. But along with my data, i need to be able to send images aswell. I tried to add my image data to a dictionary and parse that into json, but json doesnt like nscfdata. What would be the easiest way i can post my images to the server? from other posts related to this topic, people have been converting to base64. Would i have to do that, or is there another easier or faster way? if i have to encode to base64 is there any tutorial on that?
I convert it to base64. Check out this tutorial to get started!
http://www.cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
Example:
NSImage *image = // some image
NSData *data = UIImagePNGRepresentation(image);
NSString *base64EncodedString = [data base64EncodedString];
You can then send the string via JSON.

Resources