0

Webコンテンツを非同期でロードしようとしています。viewdidappearメソッドに大量のWeb呼び出しがあり、アプリが非常に応答しません。コンテンツの同期および非同期ロードの概念は理解していますが、これが非同期で行われているかどうかを判断する方法がわかりません。以下のコードは、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)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];
于 2013-02-23T08:29:59.300 に答える