how to convert NSString to NSMutableArray? - iphone

i have an NSString that is value in plist format. i download this string from url. but i dont wanna write it to a file. when the string comes Asynchronous, i want to put it to nsmutablearray.
how can i convert string (in plist format) to nsmutablearray?
there is some methods, initWithContentsOfURL, initWithContentsOfFile. but no intiwithstring.
this method works Synchronous:
NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithContentsOfURL:url];

There is a -propertyList method in NSString.
NSMutableArray* tmpArray = [[theString propertyList] mutableCopy];
...
[tmpArray release];
Note that this method will throw an exception (i.e. throw) if the string is not in plist format. To have a better error checking, try to download the data as NSData, and use the NSPropertyListSerialization methods.

Related

How to convert UIImage to JSON file in iPhone?

I have been using NSJSONSerialization class for converting fields of my object to JSON. Sadly only NSString, NSNumber, NSArray, NSDictionary, or NSNull types are supported.
As my object has one additional field, that is UIImage, I am at loss as to how to deal with it. I am sure many people have encountered this common problem, so what is best method to approach this?
You can encode UIImage data by base64, and add it to json object.
To get data from UIImage, you can use UIImagePNGRepresentation and UIImageJPEGRepresentation.
The code like this,
NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64encodedStr = base64encode(imageData);
[dict setObject:base64encodedStr forKey:#"myImage"];
//then covert dict to json object.
To restore UIImage data, just parse json object and decode the data by base64.
Hope this can help you.
You could convert your images data to a string and then write that string.
NSData *imageData = UIPNGRepresentation(image);
NSString *imageString = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
//I don't know how to use NSJSONSerialization
//[NSJSONSerialization serializeString:imageString];
NSString *base64encodedStr = [imageData base64Encoding];

Instance method '-jsonValue'not found (return type defaults to 'id')

I got problem in following statement.
NSArray *feedsData = [strFeedsResponse JSONValue];
I presume strFeedsResponse is an instance of NSString. There is no such method as JSONValue in NSString. You need NSString category and add the JSONValue method there.
You can use for example SBJson library https://github.com/stig/json-framework/, which contains NSString+SBJson.h header, which adds the JSONValue method for NSString.
This header must be than imported in the source file where you want to use the JSONValue method:
#import NSString+SBJSON.h
More about categories for example here: http://macdevelopertips.com/objective-c/objective-c-categories.html
One of two things is happening:
strFeedsResponse is not ACTUALLY an instance of an NSString. Maybe it is null or it has been initiated with an incorrect value. You can add a breakpoint to your code to check the value that is stored in strFeedsResponse before you call JSONValue on it.
You have not correctly imported the JSON framework that you are using into your class. You need to add the JSON header to your class.
Hope this helps future searchers on this error...
The reason for the error is that the current version of SBJson seems to not contain the NSString category "NSString+SBJSON.h" referred to by an earlier poster. So, you could easily write your own, or just use the SBJsonParser class directly ("address" is just an NSString containing something like "24 Elm Street, Yourtown, New Mexico"):
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *response = [NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *googleResponse = [parser objectWithString:response];
Cheers!
If you are using a webservice, then give the URL for that.
try this way...
NSArray* latestentry = (NSDictionary*)[responseString JSONValue];
NSArray *feedsData = [[strFeedsResponse JSONValue] mutableCopy];
Use this Line, it will be useful to you..
This error generally comes when method not found.Here it comes because JSONValue function is not found.
Please make sure you have included json header files where you calling this function.

How can I save NSData to my database

I have a object of UILabel
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
label1.text = #"LABEL AREA";
I want to save it in my databse(sqlite).
My idea is to convert this object to a NSData using
[NSKeyedArchiver archivedDataWithRootObject:label1]; //step1
and convert this NSData to a NSString(step2), then save that NSString to the database(step3).
When I need my UILabel. I can get the NSString from database, convert it to NSData, and use
[NSKeyedUnarchiver unarchiveObjectWithData:];
to get my UILabel.
But I have a problem in "step 2". When I use
NSString *strWithEncode = [[NSString alloc] initWithData:dataRaw encoding:NSUTF8StringEncoding];
I get a null object. I don't know the reason.
Why?
Thanks a lot!
You could either a) Store the data as a BLOB or b) Store the text of the string instead of the actual string. B seems like a better choice because you will be storing less data, and the contents of the DB will be human readable, should you need that information for debugging later on.
Because the NSData represents an encoded UILabel and not a UTF-8 encoded NSString, trying to initialize a UTF-8 string from the data will almost certainly not work. If you absolutely have to store the data as a string, try using some form of data-to-string encoding. Try using base32 or base64.

How do i put an XML source into an NSString?

I've done this with HTML, like so:
NSString *theweatherhtml = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"*URL STRING WOULD GO HERE*"]];
But when i do this with an XML file, it returns a 'Program received signal: “EXC_BAD_ACCESS”.'
Is there a different way to do this for XML files?
That method is deprecated. You need to use:
initWithContentsOfURL:encoding:error:
http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSString_Class/Reference/NSString.html
You can use NSMutableDictionary using objectforkey Or NSArray and then convert each value into related varibles. Like -
int value;
value = [[savedStock objectForKey:#"userID"] intValue];

Extracting array from NSMutableData in http response

using iphone sdk 4.0. The callback for an http request gives data as an NSData object
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the data received to our data
[theData appendData:data];
}
In my php script on the server i am returning an array as follows
var_dump($array).
How do i get my array back from the NSMutableData object 'theData' obove on my iphone.
Thanks
You have a string describing your array (or maybe several arrays?) stored as a sequence of bytes in your NSMutableData object. In order to turn it back into an array you're going to need to parse the var_dump output, which is likely to be arduous.
If you can find a library (or roll your own code) to return your data in Apple plist format, your task will be much easier: you can use
[NSPropertyListSerialization propertyListFromData:mutabilityOption:format:errorDescription:]
which takes an NSData (or NSMutableData) pointer as its first argument. Try http://code.google.com/p/cfpropertylist/ for a starting point.
From the example code at the cfpropertylist page:
$plist = new CFPropertyList();
$td = new CFTypeDetector();
$guessedStructure = $td->toCFType( $array );
$plist->add( $guessedStructure );
// and then return the plist content with
$plist->toXML()
and in your iOS code:
NSString *errorString = nil;
NSArray *array = [[NSPropertyListSerialization
propertyListFromData:theData
mutabilityOption:NSPropertyListImmutable
format:nil
errorDescription:&errorString] retain];
I would likely use YAJL on iOS, and $var = json_encode($array); in the PHP. Then in the iOS, I would parse that content from the NSData input like:
YAJLParser *parser = [[YAJLParser alloc] initWithParserOptions:YAJLParserOptionsAllowComments | YAJLParserOptionsCheckUTF8];
parser.delegate = [[[MyArrayParserDelegate alloc] init] autorelease];
[parser parse:data];
NSArray *thePhpArrayReceived = parser.delegate.resultantArray;
Please check out how to structure the delegate, and get YAJL here : Get YAJL + Readme
PHP outputs text so you will have to read that NSData as NSString and then parse out the array data according to the format specified by var_dump. As a starting point, the following code snippet should print out the array (as text) to your console:
NSString * dump = [[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding];
NSLog(#"%#", dump);
[dump release];
As Seamus Campbell points out, there are better ways of doing this. Another option would be to output XML from your PHP script, and then use Cocoa's XML parsing methods to retreive the array.