Write content of NSURL to an array - ios

I have a program that retrieves data from a link and i write it out to the Log like this.
NSURL *getURL=[NSURL URLWithString:#"link.php"];
NSError *error=nil;
NSString *str=[NSString stringWithContentsofURL:getURL encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%",str);
This prints to the log the three values from my php as expected.
However I am having a little difficulty saving this in an array which then displays it those values in a UISplitviewController (the leftcontroller side).
which is written like this
showArray=[[NSMutableArray alloc]initWithContentofURL:getURL];
then in cellForRowAtIndexPath: method is
cell.textLabel.text=[showArray object atIndex:indexPath.row];
A second thing i have tried is write myURL to an array and tried to initlize showArray with ContentsofArray like this
NSArray *retults=[NSArray arraywithContentsOFURL:getURL];
showArray=[[NSArray alloc]initWithArray:retults];
but THAT dont work
BUT if i say
showArray=[[NSMutableArray alloc]initWithObjects:#"One",#"Two",nil];
One and two shows in my leftview controller....
Would love is someone could help me with this...Thank you

Are you trying to add the contents of the URL or the URL itself ?
If you are trying to just add the URL, then use :
showArray = [#[getURL] mutableCopy];
However, if you are trying to add the contents of the URL, then the doc clearly states that the URL must represent a string representation of an array.
Furthermore :
Returns nil if the location can’t be opened or if the contents of the location can’t be parsed into an array.
EDIT :
I saw your comment on your post and your data looks like JSON data.
You should take a look at the NSJSONSerialisation class which is pretty straightforward to use (you'll find lots of example here on SO).

U have done web services perfectly, now wat u have to do is parse it to an array
First download the SBJSON files in this link
https://github.com/stig/json-framework/
Then, copy them to your workspace.
Then, in the viewController add this
#import "SBJson.h"
Your JSON data contains values in the form of dictionary
SO, to parse them
SBJsonParser * parser=[SBJsonParser new];
NSDictionary * jsonData=(NSDictionary *)[parser objectWithString:outputData];
NSArray * arr=(NSArray *)[NSDictionary objectForKey:#"animal"];
I think this will help

Related

PFFile and JSON?

In my chatting application, I'm using Parse for a user table, getting ID's, images, etc. I recently added this functionality, and I have encountered a problem. When I send a message, I create an NSDictionary with information about the message such as time, message, sender, sender objectId, etc. But, when I try to add the PFFile (image file) associated with the user, I get an error saying that PFFile cannot be converted to JSON (PubNub message format). How can I add PFFile as part of the NSDictionary used in the message to be compatible with JSON, or there might be another way.
I'm not familiar with asynchronous tasks, but in my code, I have a method - (NSDictionary *)parseMessageToDisplay:(NSDictionary *)message {} where the input would be message received from PubNub, and it would return a format better united to be displayed in a UITableView. If I added the ID of the file or user to my dictionary, how could I get my image in UIImage or NSData, and return it from my method in an NSDictionary. Sorry if this post seems long, just trying to provide a lot of information.
In order to use parse.com, PFFile in particular, you'll probably want that NSDictionary to be a PFObject instead. A PFFile reference can be saved as an attribute of a PFObject -- in fact that's the only way it can be saved.
Thanks to #danh for this suggestion, but you really saved me. Apparently Parse creates a URL for all PFFiles and I can just send that URL (NSString *) with my NSDictionary to PubNub, and then in my - (NSDictionary *)parseMessageToDisplay:(NSDictionary *)message method just use [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURLString]]; and get data from that. YAY! No long running confusing asynchronous tasks to made my day terrible!

My NSDictionary somehow has multiple values for one key

I have been attempting to debug a issue with my code, and just came upon an odd phenomenon. Found this in the debug area when a breakpoint was triggered:
Am I correct in observing that there are multiple values for this key: #"6898173"??
What are possible causes of this? I do not set those key-value pairs using the string literal, but by getting a substring of a string retrieved and decoded from a GKSession transmission.
I still have this up in the debug area in xcode, incase theres anything else there that might help.
EDIT:
By request, here is the code that would have created one of the two strings (another was created at an earlier time):
[carForPeerID setObject:[[MultiScreenRacerCarView alloc] initWithImage:[UIImage imageNamed:#"simple-travel-car-top_view"] trackNumber:[[[NSString stringWithUTF8String:data.bytes] substringWithRange:range] intValue]] forKey:[[NSString stringWithUTF8String:[data bytes]] substringFromIndex:9]];
The string in data might look something like this:
car00.0146898173
EDIT:
Code that sends the data:
[self.currentSession sendData:[[NSString stringWithFormat:#"car%i%#%#", [(MultiScreenRacerCarView *)[carForPeerID objectForKey:peerID] trackNumber], speed, [(MultiScreenRacerCarView *)[carForPeerID objectForKey:peerID] owner]] dataUsingEncoding:NSUTF8StringEncoding] toPeers:#[(NSString *)[peersInOrder objectAtIndex:(self.myOrderNumber + 1)]] withDataMode:GKSendDataReliable error:nil];
Sorry its hard to read. Its only one line.
What you're seeing is a debugger "feechure". When you have a mutable dictionary and modify it, the debugger may not show you the correct view of the object.
To reliably display the contents of an NSMutableArray or NSMutableDictionary, switch to the console and type po carForPeerID.

parsing XML located inside the project

This is the first time i'm going to parse an XML file with Xcode and it differs a bit from what I'm used to...
I read these 2 docs :
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/HandlingElements.html#//apple_ref/doc/uid/20002265-BCIJFGJI
I understand what's going on... But I still got one question. How can I do to parse an XML file which is located directly inside the project (I mean, for example in the resource file, where I usually put my images?). They usually show how to get the url of the XML file..But it's not the case here. It's going to be loaded directly on the iPad, among images and everything...
You Simply have to give the path of a local file :-
NSString *myFile= [documentsDirectory stringByAppendingPathComponent:#"youFile.xml"];
NSURL *xmlFile = [NSURL fileURLWithPath:myFile];
NSXMLParser *parser= [[NSXMLParser alloc] initWithContentsOfURL:xmlFile];
This is just an example implement your own login , use above two lines to get the path of local file.

Cut one string into two others in Objective-C

I have an NSURLRequest being made that to a server that returns a string.
string = [[NSMutableString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
receivedData is the mutable array that the downloaded data is stored in. Everything works fine.
I have now, however, added another value to that string. An example of the returned string would be 14587728000000 , 376.99. Originally it was one value so I didn't have to do any splicing. But, now that I have another value, I want to be able to separate it into two different strings.
What should I do to separate the two values into different string? Some kind of search that goes till the first space, or something like that. I have access to the server, and the string is generated in PHP so the separator can be anything.
You can do this with the NSString componentsSeparatedByString method:
NSString *string = #"14587728000000,376.99";
NSArray *chunks = [string componentsSeparatedByString: #","];
You can find some other common NSString tricks (where I found this one) here.
Use -(NSArray *)componentsSeparatedByString: and pass in the token to split by.

stringWithContentsOfFile and initWithContentsOfFile return null after several runs

I am creating an iOS app which reads in a text file and displays the contents in a UIText field.
For the 1st three consecutive runs of thee app (Restarting a new session without exiting),
the data is read in fine. However on the fourth attempt, the data returned from the file is all nulls.
I've verified the file integrity. The issue exists when using stringWithContentsOfFile or initWithContentsOfFile.
After many hours of troubleshooting, I believe the issue is somehow related to a buffer being cleared within the above mentioned methods.
Any insight regarding this issue is greatly appreciated. I've tried many things with no luck.
Here's the code I use to read in the file:
TheString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:#"My_TextFile" ofType:#"txt"] encoding:NSUTF8StringEncoding error:NULL];
Here's the code I use to display certain contents of the file (The contents are placed in an array of type NSArray):
NSArray *My_Array;
My_Array= [TheString componentsSeparatedByString:#"\n"];
/* Obtain specific data to display */
DisplayedData = [My_Array objectAtIndex:M[l]-1];
:
:
/* Display the data in the view */
MyUITextView.text = DisplayedData;
/* Log the data */
NSLog(#"%#", MyUITextView.text);
On the 4th invocation of the code above, the data returned is blank and NSLOG is returning nulls
Thanks so much for any help!
Maybe I'm a little bit late with answer, but, anyway, maybe somebody will find it useful.
OK, I have also spent a day trying to figure out why my custom class for scrollable view is working 3 times and refuse at the 4-th time... I found that the problem has quite the same attributes as yours: nested NSString objects unexpectedly disappear. Though pointers point to the same address in memory, memory is already filled with quite arbitrary objects instead my NSStrings.
And I paid attention that I created these NSStrings using the following class method:
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
So, I'm not the owner of these NSStrings.
And I assumed that to be the owner can be a solution, so I created my NSStrings through alloc and
- (id)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
instance method.
App was repaired!

Resources