Passing UIImage to JS using the native Trigger.IO API - iphone

I'm using an instance of ABAddressBookRef to access the ios address book. Ultimately I'd like to return a NSDictionary that contains names, phone numbers, and a thumbnail image. It's this last one that's giving me trouble. I can successfully include all the rest.
Here is just that UIImage being added to the dictionary contact with thumbnail as its key.
UIImage* contactThumbnail = [UIImage imageWithData:(__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail)];
NSDictionary *contact = [NSDictionary dictionaryWithObjectsAndKeys:
contactThumbnail, #"thumbnail", nil];
According to the Trigger.IO Docs I'm allowed to return a NSString, NSNumber, NSDictionary or NSArray. How would I go about returning an image? Should I convert it, just point to it, what other options exist?

I've never worked with Trigger.IO, but I'll bet when they say you can use NSString, NSNumber, NSDictionary, or NSArray, they mean ONLY those classes. A dictionary that contains objects of types not on that list, such as UIImage, won't work. That's how JSON data serialization generally works.
The solution to that problem is to serialize the image, probably into Base64 data and include that Base64 string within the dictionary, instead of the image. You can then use a data: URL within your JavaScript to reconstruct the image.

Related

Adding multiple values as a single entry into an NSMutableArray and retrieving it

I retrieve 6 values(say name, age, sex, address, id, tag) from a web service. All are string variables. I concatenate these strings and add it to an NSMutableArray. I pass this array to another class, where I need each of these strings separately. That is I need to be able to retrieve these values from the array separately. How can I do this.
Do I need to add tags like "Name", "Age" etc along with the values to make the retrieval easier. Whats the appropriate way to do it.
Edit: i concatenate it into a single string. How should I be adding my values to the collection, so that I can retrieve the elements easily.
IMO, the most appropriate way of doing what you are trying to do is using an NSMutableDictionary, that allows you to access individual elements based on their key.
Example:
loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
[loadedBuffers setObject:bufferId forKey:filePath];
...
[loadedBuffers objectForKey:filePath]
You do no strictly need using a dictionary, but it will make your life so much easier.
In your case (if I understand it correctly), I would do:
NSMutableArray* result = [NSArray arrayWithCapacity:kNUM_OF_ROWS];
NSString *name, *age, *sex....;
<for each set of strings from the web service>
<retrieve strings>
NSMutableDictionary dict = [NSMutableDictionary dictionaryWithCapacity:kNUM_OF_FIELDS];
[dict setObject:name forKey:#"name"];
...
[dict setObject:address forKey:#"address"];
[result addObject:dict];
<end_for>
return result;
By doing like this, you will be able to access sequentially each set of strings; then access each string individually.
In short, instead of encoding your set of strings by concatenating them into another string, you would expand them in a dictionary to make retrieval easier.
I would agree that the best practise here would be to use a dictionary or custom object. That way each string gets stored with its companions (e.g. you have one person's data all together) and you don't have to deal with the messy method you already have implemented. It sounds like you might want to save data, so here's a snippet to help you. If that's not what you're after, let me know and I'll modify my response to help!
Say you have a custom object class Person, where you create and manage data objects to save to disk via the app delegate. You'd do something like:
Person *newPerson = [[Person alloc] init];
[newPerson setName:#"John"];
[newPerson setAge:#"25"];
[newPerson setSex:#"M"];
[yourAppDelegate.newPersonArray insertObject:newPerson atIndex:[mainDelegate.newPersonArray count]];

Converting a photo data to nsstring returns nil

I'm allowing the users of my app to either take a pic or select one from their library. When selected I need to get the images' data and convert it to a string so I can send it to a web service.
The problem I'm currently having is that [NSString initWithData:] is returning nil when I have the encoding set to UTF8. I need to set it to UTF8 for the XML message.
NSString *dataString = [[NSString alloc] initWithData:UIImageJPEGRepresentation(theImage, 1.0) encoding:NSUTF8StringEncoding];
Thanks for any advice!
You can't convert an UIImage to NSString by using initWithData:encoding: method. This method is only for converting an string's data to NSString (an Text File for example).
If you are trying to convert any kind of binary data to NSString, there are some kind of encoding available. Base64 is widely used. Also your server should have the ability to decode what you've sent.
In addition, in most cases, send an image to server just need to POST it in binary as it used to be.

Sending array through email on iphone

Hey guys I need to send the content of an NSMutableArray through email. I have a mailing function but I'm not sure on how to place the content of the array into a NSString to be displayed on the email under each other. Is there a way to place all the content of the array into the string with maybe HTML nextline command between each array element?
NSString *emailBody = #"Need to put the body here";
Thanks
I'll suggest you convert your array into a text string using JSON. Then place the text in the email, send it away and use JSON on the receiving end to reconstruct the array.
You can get an iPhone version of JSON called TouchJSON here.
Claus
This process is known as serialization. Apple has a guide for it, that's worth reading through.
The simplest way is to call the array's description method which will return a human readable plist in a NSString.
If you need to reconstitute the array from the email. You will need save the array as xml plist using the writeToFile: method. Then read the file back in as a string. To reconstitute you will need to extract the xml from the email, put it in a NSString, write that to file, then read it back into an NSArray.
(IIRC, there used to be a way to write to NSString as if it was a file but I can't remember how to do it anymore. Probably, writing to a NSFileHandle and reading it back instantly.)
Edit:
Can you please explain more on the
array's description method please.
Like so:
NSArray *myArray=[NSArray arrayWithObjects:#"Obj1",#"Obj2",#"Obj3",nil];
NSLog(#"myArray=%#",[myArray description]);
...prints:
myArray=(
Obj1,
Obj2,
Obj3
)
For your project you can do:
NSString *arrayString=[myArray description];
The is also a descriptionWithLocale that will print the array in different languages. I don't have a ready example for that. See NSArray, NSLocale and The Locales Programming Guide

Convert NSData [UIImage] to a NSString

I am aware this question has been asked several times, but I was unable to find a definate answer that would best fit my situation.
I want the ability to have the user select an image from the library, and then that image is converted to an NSData type. I then have a requirement to call a .NET C# webservice via a HTTP get so ideally I need the resulting string to be UTF8 encoded.
This is what I have so far:
NSData *dataObj = UIImageJPEGRepresentation(selectedImage, 1.0);
[picker dismissModalViewControllerAnimated:YES];
NSString *content = [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
NSLog(#"%#", content);
The NSLog statement simply produces output as:
2009-11-29 14:13:33.937 TestUpload2[5735:207] (null)
Obviously this isnt what I hoped to achieve, so any help would be great.
Kind Regards
You can't create a UTF-8 encoded string out of just any arbitrary binary data - the data needs to actually be UTF-8 encoded, and the data for your JPEG image obviously is not. Your binary data doesn't represent a string, so you can't directly create a string from it - -[NSString initWithData:encoding:] fails appropriately in your case.
Assuming you're using NSURLConnection (although a similar statement should be true for other methods), you'll construct your NSMutableURLRequest and use -setHTTPBody: which you need to pass an NSData object to. I don't understand why you would be using a GET method here since it sounds like you're going to be uploading this image data to your web service - you should be using POST.

How do I store a string as an array in a Cocoa property list?

I am trying to save two strings. One string needs to be saved as type ARRAY in the pList and the second string needs to be saved as String in the Array.
I can use the code:
[dictionary setObject:(id)anObject forKey:(id)aKey>]
but it doesn't save it correctly. I can cast one of the strings as an array, but it still doesn't work right.
What is the proper method for saving an array to the pList?
Here is what my pList looks like:
<dict>
<key>Test One</key>
<array>
<string>A13#</string>
</array>
<key>Another Test</key>
<array>
<string>1111111111</string>
</array>
<key>Test Three</key>
<array>
<string>2222222222</string>
</array>
<key>Final Test</key>
<array>
<string>3333333333</string>
</array>
</dict>
here is the method I am using to try to
-(void)writeToFile:(NSString *)s1{
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:#"saved" ofType:#"plist"];
NSMutableDictionary *dictionary = [[[NSDictionary alloc] initWithContentsOfFile:plistPath] mutableCopy];
NSString *tempString = [NSString stringWithFormat:#"1234567"];
[dictionary setObject:tempString forKey:s1];
[dictionary writeToFile:plistPath atomically:YES];
}
You can't cast or otherwise convert a string into an array; they're separate, distinct objects. It's the same as if in real life you try to turn your dog into a station wagon, it isn't happening.
Instead, put your dog inside the station wagon (or put your string(s) inside an array). You can create the array with [NSArray arrayWithObjects:#"string1", #"string2", nil];. Stick that inside your dictionary for a given key, along with your final string for another key, save it, and you'll have a plist with an array of one or more strings.
Also, in your code example your dictionary is leaking memory. Read up on memory management in Objective-C, you're going to run into lots of crashes and performance issues until you understand it well.
You an convert a string to a single element array with
[NSArray arrayWithObject:str];
So if you want your plist to contain entries as arrays of strings, and you want just a single string as an element, then you do something like:
[dictionary setObject:[NSArray arrayWithObject:tempString] forKey:s1];
I don't actually no why you would want it this way unless you want to allow for multiple strings per key at some other time.
Also, as Marc mentioned, you are leaking the initial (unmutable) dectionary you create. Read the memory management rules at http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html.
Further, you should never write inside your application's bundle. For one thing, your application may be on a write protected volume or the current user may not have permissions to change it. For another, the file would then be shared by all users. And for a third, it would break the code signing. Instead, write the file to either the Preferences folder or the Application Support folder.
And finally, if these are intended to be user preferences of some sort, then you should use the preferences system, which allows configuring defaults and stores the preferences in the preferences folder for you. See http://developer.apple.com/documentation/Cocoa/Conceptual/UserDefaults/UserDefaults.html for more information.
The correct way to save an NSArray (by itself) to a plist file is as follows:
NSArray* anArray = ...;
[anArray writeToFile:#"/path/to/file.plist" atomically:YES];
However, you can't save an NSString as an array. Given the XML plist you provided, if you want to add entries with the same format, you can use this much simpler code:
- (void) writeToFile:(NSString *)string {
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"saved" ofType:#"plist"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[dictionary setObject:[NSArray arrayWithObject:#"1234567"] forKey:string];
[dictionary writeToFile:plistPath atomically:YES];
}
This also avoids a memory leak in your code, where the receiver of -mutableCopy escapes with a retain count of 1. (This isn't a problem under GC, but it's still bad practice.) You shouldn't need to use +[NSString stringWithFormat:], just use a string literal. If you want to use a different as the string in the array, you can either pass it in as an additional parameter, grab it from another method, etc.
This method is still brittle in that it only stores one string in the array matched with the given key — also, the method name would be better if it were more indicative of exactly what it does. Also, if there will only ever be one string value for each key, you might consider revising the plist to omit the arrays entirely, since it just chews up space and complicates the code.