Object-c/iOS:如何使用 ASynchronous 从 URL 获取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4505623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:21:56  来源:igfitidea点击:

Object-c/iOS :How to use ASynchronous to get a data from URL?

iosasynchronousnsurlconnection

提问by Webber Lai

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

我的朋友看到​​了我的代码,一部分是从 URL 获取 plist 数据

And he told me not to use Synchronous,Use ASynchronous

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

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

但我不知道如何以简单的方式做 ASynchronous

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

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

如何更改我的代码使用 ASynchronous 来获取数据?

Great thanks for all reply and answers : )

非常感谢所有回复和回答:)

回答by Manny

Short answer: You can use

简短回答:您可以使用

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

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

非正式委托协议见 NSURLConnectionDelegate(所有方法都是可选的)

Long answer:

长答案

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];
}

When you connect to server:

当您连接到服务器时:

[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

回答by X Sham

For asynchronous fetch of HTML source code, I recommend you to use AFNetworking

对于 HTML 源代码的异步获取,我建议您使用AFNetworking

1) Then subclass AFHTTPCLient, for example:

1)然后子类AFHTTPCLient,例如:

//WebClientHelper.h
#import "AFHTTPClient.h"

@interface WebClientHelper : AFHTTPClient{

}

+(WebClientHelper *)sharedClient;

@end

//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"

NSString *const gWebBaseURL = @"http://dummyBaseURL.com/";


@implementation WebClientHelper

+(WebClientHelper *)sharedClient
{
    static WebClientHelper * _sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
    });

    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    return self;
}
@end

2) Request asynchronously HTML source code, put this code in any relevant part

2) 异步请求 HTML 源代码,将此代码放在任何相关部分

NSString *testNewsURL = @"http://whatever.com";
    NSURL *url = [NSURL URLWithString:testNewsURL];
    NSURLRequest *request  = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operationHttp =
    [[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
         NSLog(@"Response: %@", szResponse );
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Operation Error: %@", error.localizedDescription);
     }];

    [[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];