acib708
acib708

Reputation: 1583

How can I get a PHP echo with NSURLConnection?

can I get some help? I'm desperate. I have a PHP script, it is sent parameters, it does some processing and then uses echo for outputting the result. I've used

[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"myPHPPathWithParameters"]] encoding:NSUTF8StringEncoding];

in the past to get the info the php echoed as a NSSTRing, and it worked, but now it doesn't. It returns a NULL NSString. Anyway, I think the correct way to do this is by implementing NSURLConnection because it implements delegate methods for watching the connection progress, etc. So, I declare a static NSMutableData *receivedData then I'm using the example in the iOS Documentation:

    NSURLRequest *req=[NSURLRequest 
                          requestWithURL:[NSURL URLWithString:@"http://myphp.php?parameters=paramteres"]
                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                          timeoutInterval:30.0];

    NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:req delegate:self];

    if (con)
        receivedData = [[NSMutableData data] retain];
    else 
        NSLog(@"Request failed to load.");

Then I implement the delegate methods (I'm also declaring NSURLConnectionDataDelegate in self):

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"RECEIVED DATA;");
    [receivedData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"received response;");
    [receivedData setLength:0];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"FINISHED;");
}

But these methods never get called! The terminal never shows any Log message showing that the delegate method executed. As I understand it, this method is called and the data appended to the receivedData and then I have to get the NSString from the receivedData once the connectionDidFinishLoading method gets called. Any suggestions? I've also tried the synchronous request class method in NSURLConnection, but that method gets the WHOLE HTML, i just want to get what the php echoes and parse it as a NSString for use inside the app :(

Upvotes: 2

Views: 1416

Answers (1)

Fry
Fry

Reputation: 6275

Transform receivedData into string

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString *myStringData = [[NSString alloc] initWithData:receivedData encoding:NSStringEncodingConversionAllowLossy];
}

And then print your string NSLog(@"MyString: %@", myStringData)

Upvotes: 2

Related Questions