ASIHTTPRequest и ASINetworkQueue и анализ JSON - PullRequest
1 голос
/ 27 сентября 2011
//
//  RootViewController.m
//  JsonPetser33
//
//  Created by ME on 9/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
//
#import "SBJson.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
//
@implementation RootViewController
//
@synthesize mNetworkQueue;
@synthesize mArrData;
//
- (void)viewDidLoad
{
    [super viewDidLoad];
    //adding right button
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                              initWithTitle:@"Load"
                                              style:UIBarButtonItemStyleDone 
                                              target:self
                                              action:@selector(loadData)];
}

-(void) loadData{
    //Stop anything already in the queue before removing it
    [[self mNetworkQueue] cancelAllOperations];
    //Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
    [self setMNetworkQueue:[ASINetworkQueue queue]];
    [[self mNetworkQueue] setDelegate:self];
    [[self mNetworkQueue] setRequestDidFinishSelector:@selector(requestFinished:)];
    [[self mNetworkQueue] setRequestDidFailSelector:@selector(requestFailed:)];
    [[self mNetworkQueue] setQueueDidFinishSelector:@selector(queueFinished:)];

    //create url request using ASIHTTPRequest
    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:[NSURL
                                              URLWithString:@"http://mikan-box.x10.bz/testing/json_test.php"]];
    [[self mNetworkQueue] addOperation:request];

    [[self mNetworkQueue] go];
}
//ASIHTTPRequest protocol?
- (void) requestFinished: (ASIHTTPRequest *)request{
    //You could release the queue here if you wanted
    if ([[self mNetworkQueue] requestsCount] == 0) {

        //Since this is a retained property, setting it to nil will release it
        //This is the safest way to handle releasing things - most of the time you only ever need to release in your accessors
        //And if you an Objective-C 2.0 property for the queue (as in this example) the accessor is generated for you
        [self setMNetworkQueue:nil];
    }
    //... Handle success
    //parsing the data
    SBJsonParser *jsonParser = [SBJsonParser new];
    NSDictionary *dicTemp = [jsonParser objectWithData:[request responseData]];//parse json
    mArrData = [dicTemp objectForKey:@"markers"];
//do something like loading data in table for now NSLog data
NSLog(@"markers: %@",mArrData);             //here the app freezes can't click button etc for a few seconds//
    NSLog(@"count %d",[mArrData count]);        // how can i enhance it?
    [jsonParser release];



    NSLog(@"Request finished");
}
- (void) requestFailed:(ASIHTTPRequest *)request{
    //You could release the queue here if you wanted
    if ([[self mNetworkQueue] requestsCount] == 0) {
        [self setMNetworkQueue:nil];
    }
    //... Handle failure
    NSLog(@"Request failed: %@",[[request error] localizedDescription]);
}

-(void) queueFinished:(ASIHTTPRequest *) queue{
    //You could release the queue here if you wanted
    if ([[self mNetworkQueue] requestsCount] == 0) {
        [self setMNetworkQueue:nil];
    }
    NSLog(@"Queue finished");
}
//


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc
{
    [mNetworkQueue reset];
    [mNetworkQueue release];
    [super dealloc];
}

@end
  • Я новичок в Objective-C и IOS .. Я использую ASIHTTPRequest, потому что он уже имеет httphandler ..
  • проблема заключается в том, когда я делаю http-запрос от данного URL(его json) он зависает во время синтаксического анализа и отображения «NSLog (@" markers:% @ ", mArrData)" .. есть ли способ улучшить этот код?
  • Я хотел бы улучшить этот код, напримерделать это в другом потоке, точно так же, как ASINetworkQueue, сделанный для запроса URL
  • Я слышал о gcd (Grand Central Dispatch), но не знаю, как или даже если это полезно ..
  • спасибо заранее

1 Ответ

0 голосов
/ 27 сентября 2011

Вы пытались не использовать ASINetworkQueue, а просто использовать простой запрос ASIHTTPRequest и использовать startAsynchronous? Например:

NSURL *url = [NSURL URLWithString:@"http://mikan-box.x10.bz/testing/json_test.php"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];

Если у вас есть несколько запросов, вы можете использовать [request setTag:tag], чтобы дифференцировать их в requestFinished:.

...