我想从PHP页面加载数据。很简单的东西,我想:
test.php的
<?php
echo "Hello World!";
?>
FirstViewController.m(来自按钮的IBAction):
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);
它没有显示任何内容,数据是(null)...... URL是正确的,如果我在Safari中打开它返回Hello World。
答案 0 :(得分:1)
问题是dataWithContentsOfURL没有阻塞,这意味着您的代码不会等待数据传递到您的应用程序。
您必须实施NSURLConnectionDelegate方法:
-(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;