2013-02-23 126 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];