对象的C / iOS版:如何使用异步摆脱URL数据? [英] Object-c/iOS :How to use ASynchronous to get a data from URL?

查看:105
本文介绍了对象的C / iOS版:如何使用异步摆脱URL数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友看到​​我的code,A部分是从URL得到的plist数据

My friend saw my code, a part is get a plist data from URL

他告诉我不要用同步,使用异步

And he told me not to use Synchronous,Use ASynchronous

但我不知道如何在简单的方式做异步

But I don't know how to do ASynchronous in simple way

这是code我在程序中使用

This is the code I use in my program

NSURL *theURL =  [[NSURL alloc]initWithString:@"http://someurllink.php" ];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:theURL
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil]; 
NSString *listFile = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];   
self.plist = [listFile propertyList];
[self.tableView reloadData];
[listFile autorelease];

我怎样才能改变我的code使用异步获取数据?

How can I change my code use ASynchronous to get the data ?

所有的回复和解答十分感谢:)

Great thanks for all reply and answers : )

推荐答案

简短的回答:您可以使用

+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;

请参阅NSURLConnectionDelegate非正规委托协议(所有的方法都是可选)

See NSURLConnectionDelegate for the informal delegate protocol (all methods are optional)

龙答案

下载数据异步并不像同步方法那样简单。首先,你必须如创建自己的数据容器一个文件容器

Downloading data asynchronously is not as straightforward as the synchronous method. First you have to create your own data container e.g. a file container

//under documents folder/temp.xml
file = [[SomeUtils getDocumentsDirectory] stringByAppendingPathComponent:@"temp.xml"]
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:file]) {
  [fileManager createFileAtPath:file contents:nil attributes:nil];
}

当您连接到服务器:

[NSURLConnection connectionWithRequest:myRequest delegate:self];

您必须填写的数据您收到异步容器:

You have to fill the container with the data you receive asynchronously:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:file];
  [fileHandle seekToEndOfFile];
  [fileHandle writeData:data];
  [fileHandle closeFile];
}

您必须使用管理中遇到的错误:

You have to manage errors encountered using:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

如果你想捕捉服务器的响应:

If you want to capture the server response:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response

手柄连接时加载完成:

Handle when connection finished loading:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

这篇关于对象的C / iOS版:如何使用异步摆脱URL数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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