0

我正在尝试异步加载网页内容。我的 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"];
4

2 回答 2

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];
}
于 2013-02-23T08:42:38.853 回答
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];
于 2013-02-23T08:29:59.300 回答