Return data after AFNetworking is done - objective-c

I got a async problem with my code. I got all of my webrequests in 1 class. One of my requests needs to return an NSMutableArray that another class needs to use. My webRequest code is here:
- (NSMutableArray*) getTournamentsInClub:(NSString *)clubGUID withDelegateViewController:(UIViewController *)viewController {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *responseArray = [[[NSMutableArray alloc] init] autorelease];
NSString *URL = [[NSString alloc]initWithFormat:#"SomeURL=%#",clubGUID];
[manager POST:URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
for (id obj in responseObject){
//NSLog(#"obj: %#",[obj valueForKey:#"CustomerName"]);
[responseArray addObject:obj];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
return responseArray;
}
I call the method from a viewController like this:
[self handleClubTournaments:[[TournamentsWebService sharedToursWS] getTournamentsInClub:
//Show load screen. (hide in handler function)
GP_MobilAppDelegate *xdelegate = [[UIApplication sharedApplication] delegate];
[xdelegate showLoadingScreen:self.clubToursTableView andStatus:NSLocalizedString(#"loadTours", #"")];
And my handleClubTournaments function looks like this:
-(void) handleClubTournaments:(id)result {
GP_MobilAppDelegate *xdelegate = [[UIApplication sharedApplication] delegate];
if([result isKindOfClass: [NSError class]]) {
// If an error has occurred, handle it
[xdelegate hideLoadingScreen];
[[TournamentsWebService sharedToursWS] showErrorMessageAccordingToFault:result];
return;
}
if([result isKindOfClass: [SoapFault class]]) {
[xdelegate hideLoadingScreen];
// If a server error has occurred, handle it
[[TournamentsWebService sharedToursWS] showErrorMessageAccordingToFault:result];
return;
}
//Do something with result...
if ([result count] > 0) {
NSLog(#"Antal klubturneringer: %d", [result count]);
//Start by removing excisting tours
[self.tournamentsSourceArray removeAllObjects];
NSMutableArray *tempArray=[NSMutableArray array];
for (GGTournamentData *t in result) { //cast object in result list and add them to array
[tempArray addObject:t];
}
self.tournamentsSourceArray = [self sortByStringDate:tempArray]; //sort by date
[tempArray release];
NSLog(NSLocalizedString(#"tourLoadet", #""));
}
[self.clubToursTableView reloadData];
[xdelegate hideLoadingScreen];
//Scroll view
if (self.tournamentsSourceArray.count > 0) { //hvis det er turneringer..
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:[self findIndexOfMonthClosestToDate]];
[self.clubToursTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
So my problem is that the NSMutableArray gets returned before my async task is done. I know a async task behaves like that, but how do i make sure that my handleClubTournaments function don't run before my webrequest(getTournamentsInClub) got some data for it?
Thanks in advance.

I don't think you know how Asynchronous operations work. The NSMutableArray will never be set, because it is returned synchronously.
In your case, I suggest you to work with delegates.
- (void)getTournamentsInClub:(NSString *)clubGUID withDelegateViewController:(UIViewController *)viewController completionBlock:(void (^)(NSMutableArray *result))completionBlock {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *responseArray = [[[NSMutableArray alloc] init] autorelease];
NSString *URL = [[NSString alloc]initWithFormat:#"SomeURL=%#",clubGUID];
[manager POST:URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
for (id obj in responseObject) {
[responseArray addObject:obj];
}
// Request finished. Call the block.
completionBlock(responseArray);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (void)handleClubTournaments {
GP_MobilAppDelegate *xdelegate = [[UIApplication sharedApplication] delegate];
[[TournamentsWebService sharedToursWS] getTournamentsInClub:^(NSMutableArray *result)
{
// Hide the Loading Indicator. Do something with the Result.
}];
// You can't access the result synchronously, therefore it's impossible to depend on it synchronously.
}
another way to return the data asynchronously would be blocks, similar to the AFNetworking solution.
You can read more about getting started with blocks here and how to use delegates here.

Related

How to show JSON data in UIView labels

About every single tutorial and example on the internet I see shows how to fetch JSON from some url and show it in Tableview. This is not my problem I know how to do that with AFNetworking framework or with native APIs.
My problem is that after I have downloaded the JSON, I want to show some of it in my UIView labels. I have actually succeeded doing this when I was trying to find a way around NSURLSession inability to cache in iOS 8. But I didn't realize that it was synchronous.
Factory.m
+ (Factory *)responseJson
{
static Factory *shared = nil;
shared = [[Factory alloc] init];
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"http://urltojson.com/file.json"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:10.0];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(#"error");
} else {
//-- JSON Parsing
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
//NSLog(#"Result = %#",result);
shared.responseJson = result;
}
return shared;
}
My question is that is it possible to use for example AFNetwoking to do the same thing? Am I missing some method that I need to call like in case of a TableView
[self.tableView reloadData];
I would like to use that framework because I need to check Reachability and it seems to implement it already.
Edit as asked to show more code
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self factoryLoad];
[self setupView];
}
- (void)factoryLoad
{
Factory *shared = [Factory responseJson];
self.titles = [shared.responseJson valueForKeyPath:#"data.title"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
});
}
- (void)setupView
{
self.issueTitleLabel.text = [self.titles objectAtIndex:0];
}
There are a couple oddities in the code you posted.
Factory, which appears to be a singleton class, should be instantiated inside a dispatch_once to ensure thread safety.
In ViewController.m, you are calling factoryLoad on the main thread, which is subsequently calling sendSynchronousRequest on the main thread. Apple's NSURLConnection Documentation warns against calling this function on the main thread as it blocks the thread, making your application unresponsive to user input.
You should not be passing in nil as the error parameter in NSJSONSerialization JSONObjectWithData:.
In your case I would recommend separating the fetching of data from the construction of your singleton object.
Factory.m
+(Factory *)sharedFactory {
static Factory *sharedFactory = nil;
dispatch_once_t onceToken;
dispatch_once(&onceToken, {
sharedFactory = [[Factory alloc] init];
});
}
-(void)fetchDataInBackgroundWithCompletionHandler:(void(^)(NSURLResponse *response,
NSData *data,
NSError *error)
completion {
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"http://urltojson.com/file.json"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:10.0];
NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:downloadQueue
completionHandler:completion];
}
Now you should be able to create a reference to the data with a guarantee that the download request has finished and thus the data will exist.
ViewController.m
-(void)factoryLoad {
[[Factory sharedFactory] fetchDataInBackgroundWithCompletionHandler:^(void)(NSURLResponse *response, NSData *data, NSError *error){
if(!error) {
NSError *error2;
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error2];
if(error2){ /* handle error */ }
self.titles = [serializedData valueForKeyPath:#"data.title"];
[Factory sharedFactory].responseJSON = serializedData;
}
else {
// handle error
}
}];
}
This will guarantee that the download has completed before you try to access any of the downloaded information. However, I've left a few things out here, including any sort of activity indicator displaying to the user that the app is doing something important in the background. The rest is, uh, left as an exercise to the reader.
Ok I took a deeper investigation into Morgan Chen's answer and how to block.
The example code took some modification but I think It works as it should and is better code.
In Factory.m
+ (Factory *) sharedInstance
{
static Factory *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
-(void)fetchDataInBackgroundWithCompletionHandler: (void(^)(BOOL success, NSDictionary *data, NSError *error)) block
{
NSString * baseURL = #"http://jsonurl.com/file.json";
AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] init];
__weak AFHTTPRequestOperationManager *weakManager = manager;
NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(#"internet!");
[weakManager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[operationQueue setSuspended:NO];
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(#"no internet");
[weakManager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
[operationQueue setSuspended:YES];
break;
default:
break;
}
}];
[manager.reachabilityManager startMonitoring];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:baseURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
block(YES, responseObject, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { // invalid request.
NSLog(#"%#", error.localizedDescription);
block(NO, nil, error);
}];
}
In ViewController.m I call this method on viewDidLoad
-(void)factoryLoad
{
[[Factory sharedInstance] fetchDataInBackgroundWithCompletionHandler:^(BOOL success, NSDictionary *data, NSError *error) {
if (success) {
NSLog(#"we have stuff");
self.responseData = data;
self.titles = [self.responseData valueForKeyPath:#"data.title"];
[self setupView];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
});
}
}];
}

Clean Code: How to avoid all those nested if/success blocks?

i was wondering how to avoid all those nested if/success blocks? So I am happy with any suggestions how to improve/encapsulate this architecture
- (void)findLocation {
// Show loader.png
[self.searchButton setImage:[UIImage imageNamed:#"loader"] forState:UIControlStateNormal];
// Request url
NSString *url = [NSString stringWithFormat:#"http://api.domain.com/someendpoint/"];
// Send http request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:url parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// If API returned error
if([responseObject objectForKey:#"error"]) {
// Show an error
// Hide loader
[self.searchButton setImage:[UIImage imageNamed:#"some_button"] forState:UIControlStateNormal];
// Skip everything else
return;
}
// If API returned data
// Init location object
Location * location = [[Location alloc] init];
location.name = [responseObject objectForKey:#"name"];
location.image_url = [responseObject objectForKey:#"image_url"];
location.url = [responseObject objectForKey:#"url"];
location.address = [responseObject objectForKey:#"address"];
// Calculate long/lat from address (API does not provide this information
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location.address completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
// Show error
} else {
// Save geo-location to location object
CLPlacemark *place = [placemarks lastObject];
location.location = CLLocationCoordinate2DMake(place.location.coordinate.latitude, place.location.coordinate.longitude);
// Present ResultViewController
ResultViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:#"ResultView"];
controller.location = location;
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:controller animated:YES completion:nil];
// Initialize region to monitor
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:location.location radius:150.0 identifier:[[NSUUID UUID] UUIDString]];
// Start monitoring new region
[self.locationManager startMonitoringForRegion:region];
// Stop UpdatingLocation
[self.locationManager stopUpdatingLocation];
// Hide loader
[self.searchButton setImage:[UIImage imageNamed:#"some_button"] forState:UIControlStateNormal];
}];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Show error
// Hide loader
[self.searchButton setImage:[UIImage imageNamed:#"some_button"] forState:UIControlStateNormal];
}
];
}
After your Show error part, return from the function. That way you can put the rest of the code outside the else clause.
As S. McConnel suggests, use first if to handle successful scenario - this makes code reading easier.
Than, as zmbq suggests, wrap it into a function.
Blocks in obj c are not really in "top 10" for their's beauty, just get used with them:)
Some tips for Objective C code style from Google :
http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml#Blocks
As a variant for your Function:
- (void)findLocation {
// Show loader.png
[self.searchButton setImage:[UIImage imageNamed:#"loader"] forState:UIControlStateNormal];
// Request url
NSString *url = [NSString stringWithFormat:#"http://api.domain.com/someendpoint/"];
// Send http request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:url parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// If API returned data
if([[responseObject objectForKey:#"ErrorCode"] intValue] == 0) {
[self setupLocation:responseObject];
// If API returned error
}
else { // Show an error
// Hide loader
[self.searchButton setImage:[UIImage imageNamed:#"surpriseme_button"] forState:UIControlStateNormal];
}
}];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Hide loader
[self.searchButton setImage:[UIImage imageNamed:#"surpriseme_button"] forState:UIControlStateNormal];
}
];
}

AFNetworking cancel downloading

I am using AFNetworking framework. So I created subclass of the AFHTTPClient:
+ (MyNetClient *)sharedClient
{
static MyNetClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:BASE_API_URL]];
});
return _sharedClient;
}
And added some methods for downloading JSON from the server.
So In my view, I start download in viewWillAppear like this:
[[MyNetClient sharedClient] getArrOfDataWithName:name
block:^(NSArray *arr) {
}];
Where:
- (void)getArrOfDataWithName:(NSString *)name block:^(NSArray *arr)block
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *params = [NSMutableDictionary
dictionaryWithObjectsAndKeys:name,#"name",nil];
[self getPath:[self urlToService:#"data/get.json"] parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"result operation%#",operation);
BOOL res = [operation isCancelled];
if (!res)
{
dispatch_async(dispatch_get_main_queue(), ^{
block(responseObject);
});
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
block(nil);
});
}];
});
}
It takes more time and user can press back, so I cancel downloading in viewDidDisappear:
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[[LRLoopNetClient sharedClient] operationQueue] cancelAllOperations];
}
But downloading operation not canceled. I added breakpoint to getArrOfDataWithName in line:
NSLog(#"result operation%#",operation);
BOOL res = [operation isCancelled];
res = NO and It is called after I leave view. I checked that:
NSInteger count = [[[LRLoopNetClient sharedClient] operationQueue] operationCount];
NSLog(#"number operations: %i",count);
In viewDidDisappear number operations:0
Please help me to cancel downloading.

AFHTTPClient subclass with custom NSMutableURLRequest objects

My app is using AFNetworking for twitter API access and I've created a twitter api client by subclassing AFHTTPClient:
#import "AFHTTPClient.h"
#interface TwitterAPIClient : AFHTTPClient
+ (TwitterAPIClient *)sharedClient;
#end
#import "TwitterAPIClient.h"
#import "AFJSONRequestOperation.h"
static NSString * const kAFTwitterAPIBaseURLString = #"http://api.twitter.com/1/";
#implementation TwitterAPIClient
+ (TwitterAPIClient *)sharedClient {
static TwitterAPIClient *_sharedClient = nil;
static dispatch_once_t TwitterAPIClientToken;
dispatch_once(&TwitterAPIClientToken, ^{
_sharedClient = [[TwitterAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kAFTwitterAPIBaseURLString]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:#"Accept" value:#"application/json"];
return self;
}
#end
If I use getPath's & postPath's on the TwitterAPIClient, the API client returns JSON responses correctly, as I register a AFJSONRequestOperation as the operation class.
However, Sometimes, I need to create custom NSMutableURLRequest requests and not use the getPath's & postPath's AFHTTPClient functions.
When I use these requests, the response is getting back from the client is standard NSData and not NSDictionary as I get from AFJSONRequestOperation.
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/account/verify_credentials.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.auth authorizeRequest:request];
AFHTTPRequestOperation* apiRequest = [[TwitterAPIClient sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, NSDictionary* responseObject) {
[self createAccount];
self.account.username = [responseObject objectForKey:#"screen_name"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate didProfileLoaded:self.account];
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (error!=nil) {
NSString* errorMessage = nil;
NSString* errorData = [error.userInfo objectForKey:NSLocalizedRecoverySuggestionErrorKey];
if (errorData!=nil) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:[errorData dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
if (json!=nil && error==nil) {
NSArray* errorMeta = [json objectForKey:#"errors"];
if (errorMeta!=nil) {
errorMessage = [[errorMeta objectAtIndex:0] objectForKey:#"message"];
}
} else {
errorMessage = errorData;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate didUpdateFailed:errorMessage];
});
}
}];
[[TwitterAPIClient sharedClient] enqueueHTTPRequestOperation:apiRequest];
Is there a way I can force these AFHTTPRequestOperation to be created as AFJSONRequestOperation objects?
Just create an AFJSONRequestOperation directly, like so:
AFJSONRequestOperation* apiRequest = [[AFJSONRequestOperation alloc] initWithRequest:request];
[apiRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// ....
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// ...
}];
More examples here and here.

AFNetworking HTTPRequestOperation need to set array from completion block but this isn't working?

I'm using AFNetworking with AFHTTPRequestOperation to pull XML data from a webservice. This is working fine and im getting the data I need but I need to split this data into objects and initialize a NSMutableArray with this data. This is working in the completion block, but just before I return the array in my method the data is gone? How do I do this?
Here is some of my code:
NSMutableArray *result = [[NSMutableArray alloc] init];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* response = [operation responseString];
NSData* xmlData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSError *xmlError;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&xmlError];
NSArray *allElements = [doc.rootElement elementsForName:#"Misc"];
for (GDataXMLElement *current in allElements)
{
NSString *titel;
NSString *tekst;
NSArray *titels = [current elementsForName:#"Titel"];
if(titels.count > 0)
{
GDataXMLElement *firstTitel = (GDataXMLElement *) [titels objectAtIndex:0];
titel = firstTitel.stringValue;
} else continue;
NSArray *teksts = [current elementsForName:#"Tekst"];
if(teksts.count > 0)
{
GDataXMLElement *firstTekst = (GDataXMLElement *) [teksts objectAtIndex:0];
tekst = firstTekst.stringValue;
} else continue;
HVMGUniversalItem *item = [[HVMGUniversalItem alloc] initWithTitel:titel AndTekst:tekst];
[result addObject:item];
}
NSLog(#"%i", result.count);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [operation error]);
}];
[operation start];
NSLog(#"%i", result.count);
return result;
What am I doing wrong? Why isn't the data present in the array when returning?
Why isn't the data present in the array when returning?
Because AFNetworking use an async pattern. So the return code will be performed before the operation will be completed.
You need to use a different approach or follow Can AFNetworking return data synchronously (inside a block)?. The latter is discouraged.
A solution could be to:
-> Create a NSOperationQueue within your class that will include your operation. Create it as a property for your class like.
#property (nonatomic, strong, readonly) NSOperationQueue* downloadQueue;
- (NSOperationQueue*)downloadQueue
{
if(downloadQueue) return downloadQueue;
downloadQueue = // alloc init here
}
-> Create a property for your array (synthesize also it)
#property (nonatomic, strong) NSMutableArray* result;
-> Wrap your code within a specific method like doOperation.
self.result = [[NSMutableArray alloc] init];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
__weak YourClass* selfBlock = self;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* response = [operation responseString];
NSData* xmlData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSError *xmlError;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&xmlError];
NSArray *allElements = [doc.rootElement elementsForName:#"Misc"];
for (GDataXMLElement *current in allElements)
{
NSString *titel;
NSString *tekst;
NSArray *titels = [current elementsForName:#"Titel"];
if(titels.count > 0)
{
GDataXMLElement *firstTitel = (GDataXMLElement *) [titels objectAtIndex:0];
titel = firstTitel.stringValue;
} else continue;
NSArray *teksts = [current elementsForName:#"Tekst"];
if(teksts.count > 0)
{
GDataXMLElement *firstTekst = (GDataXMLElement *) [teksts objectAtIndex:0];
tekst = firstTekst.stringValue;
} else continue;
HVMGUniversalItem *item = [[HVMGUniversalItem alloc] initWithTitel:titel AndTekst:tekst];
[selfBlock.result addObject:item];
}
NSLog(#"%i", result.count);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [operation error]);
}];
[downloadQueue addOperation:operation];
-> if you need to notify that result has object send a notification, use the delegate pattern, etc...
Hope that helps.