2013-02-23 128 views
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"]; 

回答

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

谢谢superglenn。我可以在我的viewdidload/viewdidappear方法中引用名称,地址和电话NSStrings吗?如果异步加载它,我该如何传递这些数据? – Brandon 2013-02-23 08:46:54

+0

如果您让viewController成为NSURLConnectionDelegate,您将从viewDidLoad运行fetchData方法,然后在connectionDidFinishLoading中获取数据时使用获取的数据(名称,地址和电话)。如果您创建另一个类作为委托,则可以使用NSNotificationCenter在完成时发布数据(并在viewController中为通知添加观察者)。 – SuperGlenn 2013-02-23 09:06:38

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)请求异步Web内容,把这个代码中任何相关部分

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