使用 NSData 从 URL 加载数据 [英] Load data from URL with NSData

查看:91
本文介绍了使用 NSData 从 URL 加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 PHP 页面加载数据.很简单的东西,我想:

I want to load data from a PHP page. Pretty simple stuff, I thought:

test.php

<?php
echo "Hello World!";
?>

FirstViewController.m(来自按钮的 IBAction):

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);

它没有显示任何内容,数据为(空)...URL 是正确的,如果我在 Safari 中打开它,它会返回 Hello World.

It doesnt show anything, data is (null)... The URL is correct, if I open it in Safari it returns Hello World.

推荐答案

问题是 dataWithContentsOfURL 没有阻塞,这意味着您的代码不会等待数据传送到您的应用程序.

The problem is dataWithContentsOfURL is not blocking, meaning your code does not wait for the data to get delivered to your app.

您必须实现 NSURLConnectionDelegate 方法:

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;

这篇关于使用 NSData 从 URL 加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆