0

This is my first API that I am calling from a demo iOS app. I just want to get the simple sentence I wrote in the php back to a label.

However the dictionary result is null when I get it in the app. How does this work? ***Corrected, code below works but not very secure

PHP file:

index.php hosted on localhost using XAMPP (http://localhost/tutorials/index.php) if I echo "hi"; it shows on the page so the server is working. 



 <?php 
if(function_exists($_GET['fe'])) {
   $_GET['fe']();
}
    function getLabel(){
        $response['name']="Hello first API ever";

        echo json_encode($response);
    }

Now in Xcode I have:

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
        //Main parse

        //Web data
        NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
        NSLog(@"%@",data);
        NSString*label=[data valueForKey:@"name"];

        _answer.text=label;

    }

    -(void)getData{

        NSURL*url=[NSURL URLWithString:@"http://localhost/tutorials/index.php?fe=getLabel"];
        NSURLRequest*request=[NSURLRequest requestWithURL:url];
        connection = [NSURLConnection connectionWithRequest:request delegate:self];

        if (connection) {
            webData=[[NSMutableData alloc]init];
        }
    }

//Clear response
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [webData setLength:0];
}

    //Append data
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        [webData appendData:data];
    }

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
        //Main parse

        //Web data

        NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
        NSLog(@"%@",data);
        NSString*label=[data valueForKey:@"name"];

        _answer.text=label;

    }

Thanks

William Falcon
  • 9,813
  • 14
  • 67
  • 110
  • 1
    Are you also implementing connection:didReceiveResponse: and connection:didReceiveData:? – rdelmar Mar 25 '13 at 22:01
  • Also, you shouldn't pass nil for the error parameter. It's there for a reason. So use it, then check if data == nil, and if it is, log the error. – rdelmar Mar 25 '13 at 22:04
  • Ok, added an error to track. Is the URL correct? how do you add a function to the url? – William Falcon Mar 25 '13 at 22:09
  • So did you get an error? I have no idea whether your URL is correct, but the error should say "bad url" if it is. I don't know what you mean by "add a function to the url" – rdelmar Mar 25 '13 at 22:15
  • Yes, then I added the if to the php and changed the url and it worked, however I don't think that is the best approach? also what if I want to send a parameter? How do I do that in the URL? – William Falcon Mar 25 '13 at 22:23

1 Answers1

1

Where's your connection:didReceiveData: method? It should be appending the received data to webData.

Mike C.
  • 601
  • 3
  • 8