为什么NSData dataWithContentsOfURL有时返回NULL值? [英] Why NSData dataWithContentsOfURL sometimes return NULL value?

查看:1136
本文介绍了为什么NSData dataWithContentsOfURL有时返回NULL值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常感谢您的将NSData字节转换为NSString?文章,特别是for @ christo16。我以前依赖于ASIHttpRequest只是从PHP服务器获取价值。现在只使用这行代码:

  NSString * pageContents = [NSData dataWithContentsOfURL:[NSURL URLWithString:@http: /www.apple.com]] 

我可以获得我想要的功能。



但是为什么有时该行会导致pageContents为NULL。我已经改变了这一行:

  NSString * fullUrl = [NSString stringWithFormat:@http://www.apple。 com]; 
NSURL * url = [[NSURL alloc] initWithString:fullUrl];
NSData * pageContents;
NSString * response = NULL;

while(response == NULL)
{
pageContents = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullUrl]];
response = [NSString stringWithUTF8String:[pageContents bytes]];
NSLog(@content =%@,response);
}

有更好的方法吗?直到现在,我没有问题。

解决方案

/ div>

如果检索数据时出错,将返回 nil



dataWithContentsOfURL:options:error:消息来找出为什么它返回nil。错误将在您传递的 NSError * 指针中返回。


I am gratefully thanks for the article Convert NSData bytes to NSString?, especially for @christo16. I was previously dependent on ASIHttpRequest just to get value from PHP server. Now using by just this line of code :

NSString *pageContents = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://www.apple.com"]]

I can get the functionality that I wanted.

But why is sometimes that line cause pageContents to be NULL. I already change that line into this :

NSString *fullUrl = [NSString stringWithFormat:@"http://www.apple.com"];
NSURL *url = [[NSURL alloc] initWithString:fullUrl];
NSData *pageContents;
NSString *response = NULL;

while(response==NULL)
{
    pageContents = [NSData dataWithContentsOfURL: [NSURL URLWithString:fullUrl]];
    response = [NSString stringWithUTF8String:[pageContents bytes]];
    NSLog(@"content = %@", response);
}

Is there any better way of doing this? Up until now, I have no problem. I just wonder whether there is a more elegant way of achieving the same result

Thanks

解决方案

It will return nil if there is an error retrieving the data.

You can use the dataWithContentsOfURL:options:error: message to find out why it's returning nil. The error will be returned in the NSError* pointer that you pass.

这篇关于为什么NSData dataWithContentsOfURL有时返回NULL值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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