Mike G
Mike G

Reputation: 751

iOS not accepting json response from php web service

I am a beginner to iOS. I have a simple web service that retrieves data from a table and sends out the results in JSON. I am trying to communicate with that web service from iOS to receive the JSON response but facing issues. This is the error i receive:

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected     content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html" UserInfo=0x7598e70

Here are my code snippets:

PHP Web Service:

$stmt = "SELECT STORE_TYPE, STORE_NAME FROM STORE WHERE STORE_ZIP = $zip";
$result = mysqli_query($this->databaseconnection, $stmt);  
$storelist = array();
$store = array();
$jsondata;
while ($row = mysqli_fetch_assoc($result)) {
  $store['STORE_TYPE'] = $row['STORE_TYPE'];
  $store['STORE_NAME'] = $row['STORE_NAME'];
  array_push($storelist,$store);
}
$jsondata = json_encode($storelist);
echo $jsondata;

I am getting the following result when i execute my php form the browser:

[{"STORE_TYPE":"GROCERY","STORE_NAME":"Walmart"},{"STORE_TYPE":"BAKERY","STORE_NAME":"Lanes Bakery"},{"STORE_TYPE":"GROCERY","STORE_NAME":"Copps"}]

iOS Code Snippet to communicate with the Web Service:

NSURL *url = [NSURL URLWithString:@"http://localhost/~Sandeep/store/store.php?rquest=getstores&zip=53715"];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation  JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"%@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];

I looked at a lot of tutorials and they all say that performing a 'json_encode' on an array in php encodes the data in JSON format and 'echo' of that is the way to go send the encoded JSON as a response. For some reason my iOS is not seeing that as JSON. I am not sure what I am missing/doing wrong here.

I really appreciate your inputs on this.

Thanks!

Upvotes: 0

Views: 715

Answers (1)

Musa
Musa

Reputation: 97672

You need to set the correct content type(use header), the error lists the acceptable types though you should use application/json

$stmt = "SELECT STORE_TYPE, STORE_NAME FROM STORE WHERE STORE_ZIP = $zip";
$result = mysqli_query($this->databaseconnection, $stmt);  
$storelist = array();
$store = array();
$jsondata;
while ($row = mysqli_fetch_assoc($result)) {
  $store['STORE_TYPE'] = $row['STORE_TYPE'];
  $store['STORE_NAME'] = $row['STORE_NAME'];
  array_push($storelist,$store);
}
$jsondata = json_encode($storelist);
header('Content-Type: application/json');
echo $jsondata;

Upvotes: 3

Related Questions