iphone - Returning data from data-grabbing class from web? -


i'm trying create class let me requested data web service. i'm stuck on how return values.

// fooclass.m // datagrabber class supposed values datagrabber = [[datagrabber alloc] init]; xmlstring = [datagrabber getdata:[nsdictionary dictionarywithobjectsandkeys:@"news", @"instruction", @"sport", @"section", nil]]; 

in example, it's supposed sports news. problem datagrabber gets data asynchronously , ends hopping several nsurlconnection delegate methods. how know in fooclass when data has been received?

the delegate pattern used strict protocol useful (that's how datagrabber find out when nsurlconnection done, right?). have written number of web apis consume xml , json information way.

// in view controller - (void) viewdidload {   [super viewdidload];   datagrabber *datagrabber = [[datagrabber alloc] init];   datagrabber.delegate = self;   [datagrabber getdata:[nsdictionary dictionarywithobjectsandkeys:@"news", @"instruction", @"sport", @"section", nil]]; } 

then in datagrabber.h file:

@protocol datagrabberdelegate @required - (void) datagrabberfinished:(datagrabber*)datagrabber; - (void) datagrabber:(datagrabber*)datagrabber failedwitherror:(nserror*)error; @end 

and in datagrabber.m:

- (void) getdata:(nsdictionary*)dict {   // ... code process "dict" here , create nsurlrequest ...   nsurlconnection *connection = [nsurlconnection connectionwithrequest:req delegate:self]; }  - (void) connectiondidfinishloading:(nsurlconnection*)connection {   // ... processing returned data ...    // tell our view controller done   [self.delegate datagrabberfinished:self]; } 

then make sure foo implements datagrabberdelegate protocol methods handle each case.

finally, datagrabber has delegate property (make sure use assign, not retain avoid retain cycles):

@property (nonatomic, assign) id<datagrabberdelegate> delegate; 

and when nsurlconnection asynchronous loads finished inside of datagrabber, call uiviewcontroller in protocol laid out above can update ui. if it's 1 request, theoretically rid of datagrabber , put inside view controller, "separate concerns" - api , view controller stay separate. generates layer, keeps "text processing code" out of view controllers (specifically json , xml parsing code).

i've done many times success - 1 other key it's provide user feedback page loading - turn on activity indicator in status bar, show them uiactivityindicator, etc., , when delegate callback comes either success or failure, rid of it.

finally, i've written more detailed blog post this: consuming web apis on iphone


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -