我正在尝试异步加载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"];

最佳答案

您可以使用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];
}

关于iphone - 异步加载Web内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15038570/

10-12 13:29