问题
I want to load data from a PHP page. Pretty simple stuff, I thought:
test.php
<?php
echo "Hello World!";
?>
FirstViewController.m (IBAction from a button):
NSString *stringURL = [NSString stringWithFormat:@"http://localhost/root/juraQuiz/test.php"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringURL]];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
It doesnt show anything, data is (null)... The URL is correct, if I open it in Safari it returns Hello World.
回答1:
The problem is dataWithContentsOfURL is not blocking, meaning your code does not wait for the data to get delivered to your app.
You will have to implement the NSURLConnectionDelegate methods:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
来源:https://stackoverflow.com/questions/22118076/load-data-from-url-with-nsdata