简体   繁体   中英

Return JSON in iOS application

I'm trying to return a simple JSON in my iOS app through PHP file.

PHP:

<?php
header('Content-Type: application/json');
$myarray = array("io" => 1, "tu" => 2);
$out = json_encode($myarray);

echo $out;

?>

iOS:

-(void)provePHP{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://mysite/myphpfile.php"]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data{

    NSError *error;

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];

    NSLog(@"%@ - %@", jsonDict, error);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"FINISH");
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error{

    NSLog(@"Error");
}

I don't understand what I do wrong. I follow a lot of code I found on this site but no results in log.

connection:didReceiveData: can be called multiple times in a connection. You should have an NSMutableData property that you keep appending data to in connection:didReceiveData: , then work with the data once it is all there in connectionDidFinishLoading .

I'd suggest adjusting your code to follow those guidelines and seeing if you still have the problem.


EDIT
If you are not getting the logs at all, you haven't properly set your class as the NSURLConnectionDelegate . See the docs for information on what the delegate pattern is and how to make your class the delegate of a framework class in Objective-C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM