Failed to load UIDocuments in separate devices - objective-c

I have created a UIDocument to wrap a custom object. The UIDocument is successfully saving to iCloud, and I am successfully loading each UIDocument when I run the app each time. However, when I attempt to run the app on a new device (iPhone 5) it will not load any UIDocument from iCloud, but I can check iCloud under Settings and see the files that are saved under my app. Does anyone have some steps to check to see why one device (iPhone 4) can load and the other (iPhone 5) cannot? I also cannot create a new UIDocument from the iPhone 5 device.
EDIT
- (void)loadObjects
{
if (!self.objects)
{
self.objects = [[NSMutableArray alloc] init];
}
NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
self.query = [[NSMetadataQuery alloc] init];
[self.query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K like 'Object_*'", NSMetadataItemFSNameKey];
[self.query setPredicate:predicate];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(queryDidFinish:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query];
[nc addObserver:self selector:#selector(queryDidUpdate:) name:NSMetadataQueryDidUpdateNotification object:self.query];
[self.query startQuery];
}
}
- (void)queryDidFinish:(NSNotification *)notification
{
[self processQueryResults:notification.object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:notification.object];
self.query = nil;
}
- (void)queryDidUpdate:(NSNotification *)notification
{
[self processQueryResults:notification.object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:notification.object];
self.query = nil;
}
- (void)processQueryResults:(NSMetadataQuery *)query
{
[query disableUpdates];
[query stopQuery];
[self.objects removeAllObjects];
[query.results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSURL *documentURL = [(NSMetadataItem *)obj valueForAttribute:NSMetadataItemURLKey];
ObjectDocument *document = [[ObjectDocument alloc] initWithFileURL:documentURL];
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
[self.objects addObject:document];
[self sortObjects];
[self.tableView reloadData];
}
}];
}];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)save:(Object *)object
{
NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
NSURL *documentsURL = [baseURL URLByAppendingPathComponent:#"Documents"];
NSURL *documentURL = [documentsURL URLByAppendingPathComponent:[NSString stringWithFormat:#"Object_%f", [object.date timeIntervalSince1970]]];
TVBFlightDocument *document = [[ObjectDocument alloc] initWithFileURL:documentURL];
document.object = object;
[document saveToURL:documentURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(#"Save succeeded.");
[_objects addObject:document];
[self sortObjects];
} else {
NSLog(#"Save failed.");
}
}];
}
}
The app on the iPhone 5 will not load the objects stored in iCloud, but iPhone 4 will load the objects from the iCloud documents.

Related

Can't pass NSManagedObjectContext to TableViewClass

I've got the problem to pass my managedobjectcontext to my tableviewcontroller. It doesn't with UserDefaults or with Notification. My storyboard is too big to pass it from my RootViewController:
AppDelegate:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
Schulung *first = [NSEntityDescription insertNewObjectForEntityForName:#"Schulung" inManagedObjectContext:self.managedObjectContext];
first.name=#"testname";
first.info=#"testinfo";
first.location=#"testlocation";
Abhaltungsdatum *firstDate = [NSEntityDescription insertNewObjectForEntityForName:#"Abhaltungsdatum" inManagedObjectContext:self.managedObjectContext];
firstDate.datum = [NSDate date];
firstDate.schulung=first;
Abhaltungsdatum *secondDate = [NSEntityDescription insertNewObjectForEntityForName:#"Abhaltungsdatum" inManagedObjectContext:self.managedObjectContext];
secondDate.datum=[NSDate date];
secondDate.schulung=first;
NSLog(#"Entities: %#",[[self.managedObjectContext.persistentStoreCoordinator.managedObjectModel entities]valueForKey:#"name"]);
// NSUserDefaults *theDefaults = [NSUserDefaults standardUserDefaults];
// NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.managedObjectContext];
// [theDefaults setObject:data forKey:#"managedObjectContext"];
// [theDefaults synchronize];
NSNotificationCenter *theCenter = [NSNotificationCenter defaultCenter];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:self.managedObjectContext forKey:#"context"];
[theCenter postNotificationName:#"managedObjectContext" object:nil userInfo:dictionary];
return YES;
}
myTableViewController:
-(void)viewDidLoad
{
[super viewDidLoad];
NSNotificationCenter *theCenter = [NSNotificationCenter defaultCenter];
[theCenter addObserver:self selector:#selector(addManagedObjectContext:) name:#"managedObjectContext" object:nil];
// NSUserDefaults *theDefaults = [NSUserDefaults standardUserDefaults];
// NSData *data = [theDefaults objectForKey:#"managedObjectContext"];
// self.managedObjectContext = [NSKeyedUnarchiver unarchiveObjectWithData:data];
// [theDefaults synchronize];
NSLog(#"Entities: %#",[[self.managedObjectContext.persistentStoreCoordinator.managedObjectModel entities]valueForKey:#"name"]);
NSFetchRequest *theRequest = self.fetchRequest;
NSFetchedResultsController *theController = [[NSFetchedResultsController alloc] initWithFetchRequest:theRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
NSError *theError = nil;
theController.delegate = self;
if([theController performFetch:&theError]) {
self.fetchedResultsController = theController;
}
else {
NSLog(#"viewDidLoad: %#", theError);
}
}
-(void)addManagedObjectContext:(NSNotification *)note{
self.managedObjectContext = [[note userInfo]valueForKey:#"context"];
}
The NSUserDefault Object gets nil when passed and the Notification doesn't come through.

iOS queuing the upload tasks

In iOS I need to call same method number of time, but the app has to wait until the method completed it's first task. (I can not use bool value to check whether the function is running or not).
How can I queue the request or wait until it's previous task has finished? Is there a way I can use NSOperation or NSThread?
Thanks
This is my method I need to call multiple times
- (void)fetchJobs
{
dispatch_queue_t queueLocal = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t groupLocal = dispatch_group_create();
UIApplication *app = [UIApplication sharedApplication];
NSTimeInterval backgroundTime = app.backgroundTimeRemaining;
NSLog(#"Background task remain time: %g seconds", (double)backgroundTime);
[[NSNotificationCenter defaultCenter] postNotificationName:#"UPLOAD_PROCESS_START" object:nil];
self.assetUpdateTaskID = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self endTask];
});
}];
dispatch_group_async(groupLocal, queueLocal, ^{
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Files" inManagedObjectContext:self.managedObjectContext];
//Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat: #"uploaded like %#", [NSString stringWithFormat:#"0"]];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSError *error = nil;
//fetch the records and handle an error
NSArray *fetchResults = [self.managedObjectContext executeFetchRequest:request error:&error];
if (fetchResults == nil) {
NSLog(#"File Data fetching error : %#", [error localizedDescription]);
}
else{
if ([fetchResults count] > 0) {
dispatch_apply([fetchResults count], queue, ^(size_t i){
NSLog(#"Loop count %zu", i);
Files *file = [fetchResults objectAtIndex:i];
self.manageObjectForFiles = file;
NSLog(#"Fetched File details -> Name: %# & status: %#" , file.fileName, file.uploaded);
BOOL uploaded = [self filePosting:file.fileName];
if (uploaded) {
[self.managedObjectContext deleteObject:file];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"File table update error : %#", [error description]);
}
}
});
/*
for (int i = 0; i < [fetchResults count]; i++) {
}*/
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
int remainJobs = [self fetchFileTableCount];
if (remainJobs > 0) {
[UIApplication sharedApplication].applicationIconBadgeNumber = remainJobs;
[[NSNotificationCenter defaultCenter] postNotificationName:#"UPLOAD_REMAIN" object:nil];
}
else{
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[[NSNotificationCenter defaultCenter] postNotificationName:#"UPLOAD_PROCESS_COMPLETED" object:nil];
NSLog(#"-----------------------------------------------");
NSLog(#"There are no more uploads");
NSLog(#"-----------------------------------------------");
}
[self endTask];
});
});
dispatch_release(groupLocal);
}
You'd didn't say if the calls have to be serial of if they can be concurrent. If concurrent you can use NSOperation's mainQueue, suspend it, add all but the first call, then in your method, at the end, see if the queue is suspended and if so resume it.
With Grand Central Dispatch (CGD) you can more easily create a serial dispatch queue, and sort of do the same - suspend it, add all but the first call wrapped in a block, then at the end of the first call unsuspend the queue. If you need this to run on the main thread you can have the serial queue tied to the main GCD queue.

How to Sync an NSDocument from Mac osx to iPad/iPhone with iCloud

I have seen iCloud Document sample code for iOS and I used it to sync a uidocument to and from iCloud and now I am trying to sync iCloud with an nsdocument on a Mac OSX app which doesn't have UIDocument.
I tried to change UIDocument to NSDocument but all the methods of syncing with icloud are different. I haven't found any sample code or tutorials except for the documentation from apple which is very confusing and not well written.
For example, the method below, from UIDocument on iOS does not exist in NSDocument on OS X:
//doc is an instance of subclassed UIDocument
[doc openWithCompletionHandler:nil];
The Apple Documentation provides this code for OS X:
- (void)checkIfCloudAvaliable {
NSURL *ubiquityContainerURL = [[[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:#"Documents"];
if (ubiquityContainerURL == nil) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(#"iCloud does not appear to be configured.", #""),
NSLocalizedFailureReasonErrorKey, nil];
NSError *error = [NSError errorWithDomain:#"Application" code:404
userInfo:dict];
[self presentError:error modalForWindow:[self windowForSheet] delegate:nil
didPresentSelector:NULL contextInfo:NULL];
return;
}
dest = [ubiquityContainerURL URLByAppendingPathComponent:
[[self fileURL] lastPathComponent]];
}
- (void)moveToOrFromCloud {
dispatch_queue_t globalQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^(void) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error = nil;
// Move the file.
BOOL success = [fileManager setUbiquitous:YES itemAtURL:[self fileURL]
destinationURL:dest error:&error];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (! success) {
[self presentError:error modalForWindow:[self windowForSheet]
delegate:nil didPresentSelector:NULL contextInfo:NULL];
}
});
});
[self setFileURL:dest];
[self setFileModificationDate:nil];
}
How can I sync between iOS and OS X (because NSDocument does not exists on iOS, and UIDocument does not exist on OS X)? Does anyone know where I can find a sample for Mac OSX (NSDocument syncing)?
I managed to get it working! Here's my code from the subclassed nsdocument file on OS X:
Header file:
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#interface subclassedNSDocument : NSDocument
#property (strong) NSData *myData;
#end
Implementation file:
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
BOOL readSuccess = NO;
if (data)
{
readSuccess = YES;
[self setMyData:data];
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"dataModified"
object:self];
return readSuccess;
}
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
if (!myData && outError) {
*outError = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileWriteUnknownError userInfo:nil];
}
return myData;
}
and in the AppDelegate.m file:
#define kFILENAME #"mydocument.dox"
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
NSLog(#"iCloud access at %#", ubiq);
// TODO: Load document...
[self loadDocument];
}
else
{
NSLog(#"No iCloud access");
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(dataReloaded:)
name:#"dataModified" object:nil];
}
- (void)update_iCloud
{
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:kFILENAME];
self.doc.myData = [NSKeyedArchiver archivedDataWithRootObject:[#"Your Data Array or any data", nil]];
[self.doc saveToURL:ubiquitousPackage ofType:#"dox" forSaveOperation:NSSaveOperation error:nil];
}
- (void)loadData:(NSMetadataQuery *)query {
if ([query resultCount] == 1) {
NSMetadataItem *item = [query resultAtIndex:0];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
NSLog(#"url = %#",url);
subclassedNSDocument *doc = [[subclassedNSDocument alloc] initWithContentsOfURL:url ofType:#"dox" error:nil];
[doc setFileURL:url];
self.doc = doc;
}
else {
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:kFILENAME];
dataUrls *doc = [[dataUrls alloc] init];
[self.doc setFileURL:ubiquitousPackage];
self.doc = doc;
[self.doc saveToURL:ubiquitousPackage ofType:#"dox" forSaveOperation:NSSaveOperation error:nil];
}
}
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
_query = nil;
[self loadData:query];
}
- (void)loadDocument {
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
_query = query;
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred = [NSPredicate predicateWithFormat: #"%K == %#", NSMetadataItemFSNameKey, kFILENAME];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
}
- (void)dataReloaded:(NSNotification *)notification
{
self.doc = notification.object;
NSArray *arrFromCloud = [NSKeyedUnarchiver unarchiveObjectWithData:self.doc.myData];
//Update you UI with new data
}
The only thing that I haven't got working is that if I change the data of the document on the iPad, the Mac app doesn't call the readFromData method for to update from iCloud, does anyone know what I am missing?
On iOS, the equivalent method, loadFromContents, is called automatically on every change of the UIDocument in iCloud. On OS X the readFromData is called once on load but never called again.
Hope my code can help, for me it is working one way from Mac to iPad.
I think NSMetadataQueryDidUpdateNotification is what you are looking for to detect document update.
This can be used just like NSMetadataQueryDidFinishGatheringNotification.
If you are dealing with files in addition to core data. Here is a better tutorial
http://samvermette.com/312

applicationWillResignActive notification uncaught on device

I'm trying to save a simple string on a simple .plist file when the application is closing.
This is my code:
- (void)viewDidLoad {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
self.kmOld.text = [array objectAtIndex:0];
[array release];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:NULL];
[super viewDidLoad];
}
Then follow the applicationWillResignActive method:
- (void)applicationWillResignActive:(NSNotification *)notification {
NSString *text = [[NSString alloc]initWithFormat:#"%#",kmNew.text];
NSLog(#"%#",text);
if ([text intValue]>0) {
NSArray *array = [[NSArray alloc] initWithObjects:text, nil];
BOOL success = [array writeToFile:[self dataFilePath] atomically:YES];
NSLog(#"%d",success);
[array release];
}
[text release];
}
This work fine on the simulator, but it seems to be ignored by the device...
Where is the problem? Thanks...
Take a look at http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/ for a good overview of the UIApplication lifecycle. Depending on the iOS version your app is running on and the action causing your app to terminate/background you may not be listening for the correct notification and may need to observe UIApplicationWillTerminateNotification as well.

NSNotificationCenter notifications not sent/received

// Question was answered, basicly I should sleep more / code less :)
When my app starts i first load a splash screen, this splashscreen will start a dataDownload when the screen itself is done loading:
Splash.m
#implementation Splash
- (id) init
{
self = [super init];
_lblFunds = [[UILabel alloc] initWithFrame:CGRectMake(350, 330, 324,28)];
_lblFunds.numberOfLines = 1;
[_lblFunds setFont:[UIFont systemFontOfSize:24.0]];
[_lblFunds setTextAlignment: UITextAlignmentCenter];
[_lblFunds setText:#".. Fondsen .."];
[self.view addSubview:_lblFunds];
_lblObjects = [[UILabel alloc] initWithFrame:CGRectMake(350, 360, 324,28)];
_lblObjects.numberOfLines = 1;
[_lblObjects setFont:[UIFont systemFontOfSize:24.0]];
[_lblObjects setTextAlignment: UITextAlignmentCenter];
[_lblObjects setText:#".. Vastgoed Objecten .."];
[self.view addSubview:_lblObjects];
_lblCustomers = [[UILabel alloc] initWithFrame:CGRectMake(350, 390, 324,28)];
_lblCustomers.numberOfLines = 1;
[_lblCustomers setFont:[UIFont systemFontOfSize:24.0]];
[_lblCustomers setTextAlignment: UITextAlignmentCenter];
[_lblCustomers setText:#".. Clienten .."];
[self.view addSubview:_lblCustomers];
return self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(fundsLoaded) name:#"FundsDone" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(customersLoaded) name:#"CustomersDone" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(objectsLoaded) name:#"ObjectsDone" object:nil];
}
- (void) fundsLoaded
{
[_lblFunds setText:[NSString stringWithFormat:#"Fondsen geladen: %d",[[DataManager sharedInstance] fundsCount]]];
}
- (void) objectsLoaded
{
[_lblObjects setText:[NSString stringWithFormat:#"Vastgoed Objecten geladen: %d",[[DataManager sharedInstance] objectsCount]]];
}
- (void) customersLoaded
{
[_lblCustomers setText:[NSString stringWithFormat:#"Clienten geladen: %d",[[DataManager sharedInstance] customersCount]]];
}
- (void) viewDidLoad
{
[super viewDidLoad];
[[DataManager sharedInstance] getData];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
The DataManager will then proceed to use its instance of DataLoader to load and parse the data in a seperate thread, whenever data is parsed and stored away a Notification is sent from the DataLoader. If worked with the Notifications a lot before but this time it just will not work and I cannot seem to figure out why not. There is no error or anything, but the functions as set in the observers are never called. Any ideas on what is wrong are very much welcome, I have read quite a few threads on here, and other sites but haven't found my answer yet.
DataManager.m
#implementation DataManager
static DataManager* _dataManager = nil;
static DataLoader *_dataLoader = nil;
static bool _dataLoaded = FALSE;
- (int) fundsCount
{
return _dataLoader.funds_count;
}
- (int) objectsCount
{
return _dataLoader.objects_count;
}
- (int) customersCount
{
return _dataLoader.customers_count;
}
+ (DataManager *) sharedInstance{
#synchronized([DataManager class])
{
if(!_dataManager)
{
_dataManager = [[super alloc] init];
_dataLoader = [[DataLoader alloc] init];
}
return _dataManager;
}
return nil;
}
- (void) loadDataSucces
{
_dataLoaded = TRUE;
}
- (void) _getData
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if(_dataLoader)
{
[_dataLoader loadData];
} else
{
NSLog(#"DataLoader not initialized");
}
[pool drain];
}
- (void) getData
{
[NSThread detachNewThreadSelector:#selector(_getData) toTarget:self withObject:nil];
}
#end
DataLoader.m
- (void) parseData: (NSString *) jsonString
{
NSError *err;
SBJsonParser *parser = [[SBJsonParser alloc] init];
id object = [parser objectWithString:jsonString error:&err];
[jsonString release];
if (!object) {
} else {
//funds
id funds = [object objectForKey:#"fondsen"];
[self deleteAllEntitiesOfType:#"Fund"];
int nr = 0;
for (NSDictionary *i in funds)
{
NSString *naam = [i objectForKey:#"naam"];
if([naam length] > 2)
{
NSManagedObjectContext *context = [(CatalogusAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
Fund *f = [NSEntityDescription insertNewObjectForEntityForName:#"Fund" inManagedObjectContext: context];
NSString *integertje = [i objectForKey:#"oid"];
int in = [integertje integerValue];
[f setOid: [NSNumber numberWithInt: in ]];
[f setNaam: naam];
NSError *error = nil;
if( ![context save: &error ])
{
NSLog(#"Error: %#", [[error userInfo] valueForKey:#"ErrorString"]);
} else
{
nr++;
}
}
}
funds_count = nr;
[[NSNotificationCenter defaultCenter] postNotificationName:#"FundsDone" object:nil];
//objects
if( true )
{
id objects = [object objectForKey:#"vastgoedobjecten"];
[self deleteAllEntitiesOfType:#"Object"];
nr = 0;
NSManagedObjectContext *context = [(CatalogusAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
for (NSDictionary *i in objects)
{
Object *o = [NSEntityDescription insertNewObjectForEntityForName:#"Object" inManagedObjectContext: context];
[o setFondsOid:[NSNumber numberWithInt: [ [i objectForKey:#"fondsOid"] integerValue] ]];
[o setOid: [NSNumber numberWithInt: [ [i objectForKey:#"oid"] integerValue] ]];
[o setAdres:[i objectForKey:#"adres"]];
[o setPostcode:[i objectForKey:#"postcode"]];
[o setPlaats: [ i objectForKey:#"plaats"]];
[o setProvincie:[i objectForKey:#"provincie"]];
[o setStatus:[i objectForKey:#"status"]];
[o setSegment:[i objectForKey:#"segment"]];
[o setOppervlakte:[NSNumber numberWithInt: [ [i objectForKey:#"oppervlakte"] integerValue] ]];
[o setBelangrijksteHuurder:[i objectForKey:#"belangrijksteHuurder"]];
[o setWeging:[i objectForKey:#"weging"]];
[o setLongitude:[NSNumber numberWithDouble: [ [i objectForKey:#"longitude"] doubleValue] ]];
[o setLatitude:[NSNumber numberWithDouble: [ [i objectForKey:#"latitude"] doubleValue] ]];
NSError *error = nil;
if( ![context save: &error ])
{
NSLog(#"Error: %#", [[error userInfo] valueForKey:#"ErrorString"]);
} else
{
nr++;
}
}
objects_count = nr;
NSLog(#"ObjectsLoaded");
[[NSNotificationCenter defaultCenter] postNotificationName:#"ObjectsDone" object:nil];
}
//customers
if( true )
{
id custs = [object objectForKey:#"klanten"];
[self deleteAllEntitiesOfType:#"Customer"];
nr = 0;
NSManagedObjectContext *context = [(CatalogusAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
for (NSDictionary *i in custs)
{
Customer *c = [NSEntityDescription insertNewObjectForEntityForName:#"Customer" inManagedObjectContext: context];
[c setOid: [NSNumber numberWithInt: [ [i objectForKey:#"oid"] integerValue] ]];
[c setFondsOid:[NSNumber numberWithInt: [ [i objectForKey:#"fondsOid"] integerValue] ]];
[c setNaam: [i objectForKey:#"naam"]];
NSError *error = nil;
if( ![context save: &error ])
{
NSLog(#"Error: %#", [[error userInfo] valueForKey:#"ErrorString"]);
} else
{
nr++;
}
}
customers_count = nr;
[[NSNotificationCenter defaultCenter] postNotificationName:#"CustomersDone" object:nil];
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"DataReady" object:nil];
}
- (void) loadData{
NSString *urlString = #"URL";
NSDate *startDownload = [NSDate date];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *dataFeed = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
if(error){
NSString *d = [ error description ];
NSLog(#"error: %#",d);
} int bytes = [dataFeed length];
NSDate *endDownload = [NSDate date];
NSString *data = [[NSString alloc] initWithData:[NSData decompress:dataFeed] encoding:NSStringEncodingConversionExternalRepresentation];
int string = [data length];
NSDate *endDecompress = [NSDate date];
NSLog(#"Download data: %f - Decompress: %f - BytesDownloaded: %d", [endDownload timeIntervalSinceDate:startDownload], [endDecompress timeIntervalSinceDate:endDownload], bytes);
[[NSNotificationCenter defaultCenter] postNotificationName:#"DownloadDone" object:nil];
[self parseData:data];
}
In init, you should put your registration code BEFORE the return statement. Otherwise it will never run.
Cheers!