Retrieve data from PHP page

Discussion in 'iOS Programming' started by wasimkham, Aug 14, 2010.

  1. wasimkham macrumors newbie

    Aug 14, 2010

    I'm very new to iPhone app development and I wanted to know how I would go about retrieving data from a PHP page. The reason for this is so I can access and save information to and from my MySQL Database. I have had a go at doing this myself but results are less that perfect. Here is some of my code;

    - (void)viewDidLoad {
    	theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/test.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    	theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    	if (theConnection) {
    		// Create the NSMutableData to hold the received data.
    		// receivedData is an instance variable declared elsewhere.
    		receivedData = [[NSMutableData data] retain];
    	} else {
    		// Inform the user that the connection failed.
        [super viewDidLoad];
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    	self.title = @"First Screen";
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
        // Append the new data to receivedData.
        // receivedData is an instance variable declared elsewhere.
        [receivedData appendData:data];
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
        // do something with the data
        // receivedData is declared as a method instance elsewhere
        NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
        // release the connection, and the data object
        [connection release];
        [receivedData release];

    Now this all works fine and my log outputs the length of the data. But i'm not sure how to access the actual data downloaded as i've tried looking at all the properties of the NSData object and none of them are the contents of the file.

    Also what is the best way to format the data from PHP? Could I serialize it and unserialize in Cocoa to get an array? Or is XML the best option?

    Thanks very much for the help!
  2. jnic macrumors 6502a

    Oct 24, 2008
    Your NSData object is the contents of the file. To get a string representation (assuming the data is just text) check out initWithData:encoding: from the NSString Class Reference.
  3. wasimkham thread starter macrumors newbie

    Aug 14, 2010
    Thanks very much for that, worked perfectly. I also found framework for an XML parser which is great for translating the information.
  4. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    The code you show saves the data into an NSData object. This won't work for big files as you'll run out of memory. Instead you'll need to write the data to a file as it comes in.

Share This Page