异步加载Web内容

时间:2013-02-23 08:16:39

标签: iphone ios objective-c xcode asynchronous

我正在尝试异步加载Web内容。我的viewdidappear方法中有大量的网络电话,我的应用程序非常反应迟钝。我理解内容的同步和异步加载的概念,但不知道如何判断是否异步完成。下面的代码只是嵌入在我的viewdidappear方法中,我假设它是同步加载的。我如何编辑它以使其异步加载?谢谢大家!

NSString *strURLtwo = [NSString stringWithFormat:@"http://website.com/json.php?
id=%@&lat1=%@&lon1=%@",id, lat, lon];

NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];

NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0 
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];

NSString *name = [element1 objectForKey:@"name"];
NSString *address = [element1 objectForKey:@"address"];
NSString *phone = [element1 objectForKey:@"phone"];

2 个答案:

答案 0 :(得分:2)

您可以使用NSURLConnectionDelegate:

// Your public fetch method
-(void)fetchData
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://website.com/json.php?id=%@&lat1=%@&lon1=%@",id, lat, lon]];

    // Put that URL into an NSURLRequest
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    // Create a connection that will exchange this request for data from the URL
    connection = [[NSURLConnection alloc] initWithRequest:req
                                                 delegate:self
                                         startImmediately:YES];
}

实施委托方法:

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    // Add the incoming chunk of data to the container we are keeping
    // The data always comes in the correct order
    [jsonData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
    // All data is downloaded. Do your stuff with the data
    NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
    NSDictionary *element1 = [readJsonArray objectAtIndex:0];

    NSString *name = [element1 objectForKey:@"name"];
    NSString *address = [element1 objectForKey:@"address"];
    NSString *phone = [element1 objectForKey:@"phone"];

    jsonData = nil;
    connection = nil;
}

// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
    connection = nil;
    jsonData = nil;
    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error     localizedDescription]];

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertView show];
}

答案 1 :(得分:1)

对于异步Web内容加载,我建议您使用AFNetworking。它将来解决你很多网络的头痛问题。怎么做:

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://whateverBaseURL.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)异步请求您的网站内容,将此代码放在任何相关部分

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

         //PUT your code here
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Operation Error: %@", error.localizedDescription);
     }];

    [[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];