Load data from URL with NSData

浪尽此生 提交于 2020-01-15 11:00:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!