I want to save some texts in textfields whenever the user goes to the background i think i wrote everything correctly since i followed many question/answers. However when I close my app my app doesn't save the text or even create a plist so when i reopen it, the textfields are empty. Here is the code:
RootViewController.h:
#interface RootViewController: UIViewController <UITextFieldDelegate> {
UITextField *textField1;
UITextField *textField2;
UITextField *textField3;
UITextField *textField4;
}
#property (nonatomic, retain) UITextField *textField1, *textField2, *textField3, *textField4;
#end
RootViewController.m:
#import "RootViewController.h"
#implementation RootViewController
#synthesize textField1, textField2, textField3, textField4;
...
- (UILabel*)addNewLabel:(NSString*)_text
{
//Initializing TextViews
}
....
- (NSString *) saveFilePathB
{
NSString *path = #"/Applications/AppDissassembler.app/Cache/savefileb.plist";
return path;
}
- (void)loadView {
self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
self.view.backgroundColor = [UIColor whiteColor];
//creating textfields
self.textField1 = [self addNewTextfield:60:80:175:true:#"Binary Name Here":1];
self.textField2 = [self addNewTextfield:60:145:200:true:#"Offset Here (0xOffset)":2];
self.textField3 = [self addNewTextfield:75:210:175:false:nil:3];
self.textField4 = [self addNewTextfield:75:310:175:false:nil:4];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSArray *values = [[NSArray alloc] initWithObjects:self.textField1.text,self.textField2.text,self.textField3.text,self.textField4.text,nil];
NSFileHandle *fout1;
[[NSFileManager defaultManager] createFileAtPath:[self saveFilePathB] contents:nil attributes:nil];
//open output file for writing
fout1 = [NSFileHandle fileHandleForWritingAtPath:[self saveFilePathB]];
[values writeToFile:[self saveFilePathB] atomically:YES];
[values release];
}
- (void)viewDidLoad
{
NSString *myPath = [self saveFilePathB];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
self.textField1.text = [values objectAtIndex:0];
self.textField2.text = [values objectAtIndex:1];
self.textField3.text = [values objectAtIndex:2];
self.textField4.text = [values objectAtIndex:3];
[values release];
}
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationDidEnterBackground:) name:#"UIApplicationDidEnterBackgroundNotification" object:myApp];
[super viewDidLoad];
}
- (void)dealloc {
[textField1 release];
[textField2 release];
[textField3 release];
[textField4 release];
[super dealloc];
}
#end
If I change this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationDidEnterBackground:) name:#"UIApplicationDidEnterBackgroundNotification" object:myApp];
to this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:myApp];
I get an error which says that UIApplicationDidEnterBackgroundNotification wasn't declared.
It wont run in method you try, so in UIApplicationDidEnterBackground delegate. All you have to do is handle your process while going into background with beginBackgroundTaskWithExpirationHandler. See this topic: topic
The second version you tried, where UIApplicationDidEnterBackgroundNotification is an identifier not a literal string, is the correct way to use this feature. It should be defined in UIApplication.h.
You say you are compiling on the iPhone itself, so it sounds like the development environment you have there is lacking this definition. I haven't tried that myself, so can't be sure.
Once you have got past the compilation error I would recommend to use NSLog to see where your code has got to, because this is easier than looking for the file to be created.
Related
I'm having some kind of problems with one thing, i'm making an app and i have a webview that shows a pdf file, and i have a button if clicked will call an UIDocumentInteractionController (open the pdf in a new window).
I will leave screenshots to make it easier:
When i open the app:
http://imgur.com/dpIEd
After i open the UIDocumentInteractionController:
http://imgur.com/VYV2N
Here's the code too
.h file
#interface pdfView : UIViewController <UIDocumentInteractionControllerDelegate>
{
IBOutlet UIActivityIndicatorView *loading;
IBOutlet UIWebView *Wview;
UIDocumentInteractionController *controller;
}
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *loading;
#property (nonatomic, retain) IBOutlet UIWebView *Wview;
#property (nonatomic, retain) UIDocumentInteractionController *controller;
-(void)buttonPressed;
-(IBAction)open_in:(id)sender;
-(IBAction)back:(id)sender;
#end
.m file
#import "pdfView.h"
#implementation pdfView
#synthesize loading,Wview;
#synthesize controller;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)viewDidLoad
{
[loading startAnimating];
[super viewDidLoad];
Wview.scalesPageToFit = TRUE;
Wview.multipleTouchEnabled = TRUE;
[Wview setOpaque:NO];
NSString *path = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[Wview loadRequest:request];
[loading stopAnimating];
}
-(IBAction)open_in:(id)sender
{
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileToOpen]];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
-(IBAction)back:(id)sender
{
[self.view removeFromSuperview];
}
-(void)buttonPressed
{
//[self.view removeFromSuperview];
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileToOpen]];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
return self.view.frame;
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
{
[self.controller autorelease];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[super dealloc];
[Wview release];
[loading release];
}
#end
Thanks in advance.....
I would suggest not useing the webview and using a pdf app (ibook, cloudreader) like this.
//name of pdf
NSString * pathString = #"userguide";
//get pdf path
NSString * filePath = [[NSBundle mainBundle] pathForResource:pathString ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
self.docController = [UIDocumentInteractionController interactionControllerWithURL:url];
BOOL isValid = [self.docController presentOpenInMenuFromRect:self.handBookLaunch.frame inView:self.view animated:YES];
if (!isValid) {
NSString * messageString = [NSString stringWithFormat:#"No PDF reader was found on your device. Please download a PDF reader (eg. iBooks)."];
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:messageString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
Solved, added this code for layout verification:
-(void) viewWillAppear:(BOOL)animated
{
CGRect arect=[[UIScreen mainScreen]applicationFrame];
CGRect anotherrect=[[UIApplication sharedApplication]statusBarFrame];
if(self.view.center.y==arect.size.height/2)
self.view.center=CGPointMake(self.view.center.x, self.view.center.y+anotherrect.size.height); // fix silliness in IB that makes view start 20 pixels higher than it should on iPhone
}
source: https://discussions.apple.com/thread/2658315?start=0&tstart=0
I am trying to use iCloud with my iOS app. I have the app working on the individual devices but when I added iCloud nothing happened. I have looked all over the web and have found only one example which I did not understand. My app is iOS 5.0 and use core data to store the pages. Below is my app delegate and my view which I display it in. Sorry for the lack of knowledge when it comes to iPhone dev. Please help.
http://goddess-gate.com/dc2/index.php/post/452
thank you
If anyone know/has a full working project of iCloud+CoreData I belive I can figure it out. Right now I just have code snip it's which I don't even know how they get called... If I have a full project I can step through it, so I can fully understand how it works.
The problem is I don't think anything is being called to update the view with the data and I don't belive it is sending it to the cloud but I don't know what to call...
PageFlipperAppDelegate.h
#import <UIKit/UIKit.h>
#import "PageView.h"
#import "SlideShowViewController.h"
#import "PagesCollectionViewController.h"
#import "UiWindowSubclass.h"
#interface PageFlipperAppDelegate : UIResponder <UIApplicationDelegate>
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, retain, readonly) PagesCollectionViewController *collectionViewController;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
PageFlipperAppDelegate.m
#import "PageFlipperAppDelegate.h"
#implementation PageFlipperAppDelegate
#synthesize window;
#synthesize managedObjectContext, managedObjectModel, persistentStoreCoordinator,collectionViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
[NSThread sleepForTimeInterval:2.75];
collectionViewController = [[PagesCollectionViewController alloc] initWithManagedObjectContext:[self managedObjectContext]];
[(UINavigationController *)[[self window] rootViewController] pushViewController:collectionViewController animated:NO];
[collectionViewController release];
[[self window] makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
//stopping timer since we're going to background
// [(UiWindowSubclass *)self.window stopTimer];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application { [self saveContext]; }
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application { [self saveContext];
}
- (void)dealloc
{
[window release];
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[super dealloc];
}
- (void)awakeFromNib
{
}
- (void)saveContext
{
NSError *error = nil;
if ([self managedObjectContext])
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
//if (IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(#"5.0")) {
NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc performBlockAndWait:^{
[moc setPersistentStoreCoordinator: coordinator];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
}];
managedObjectContext = moc;
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (!managedObjectModel)
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"PageFlipper" withExtension:#"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil)
{
return persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"PageFlipper.sqlite"];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSPersistentStoreCoordinator* psc = persistentStoreCoordinator;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
// Migrate datamodel
NSDictionary *options = nil;
// this needs to match the entitlements and provisioning profile
NSURL *cloudURL = [fileManager URLForUbiquityContainerIdentifier:#"G88FQ4WK29.com.brandonsdesigngroup.3Doodles"];
NSString* coreDataCloudContent = [[cloudURL path] stringByAppendingPathComponent:#"data"];
if ([coreDataCloudContent length] != 0) {
// iCloud is available
cloudURL = [NSURL fileURLWithPath:coreDataCloudContent];
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
#"3Doodles.store", NSPersistentStoreUbiquitousContentNameKey,
cloudURL, NSPersistentStoreUbiquitousContentURLKey,
nil];
} else {
// iCloud is not available
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
}
NSError *error = nil;
[psc lock];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[psc unlock];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"asynchronously added persistent store!");
[[NSNotificationCenter defaultCenter] postNotificationName:#"RefetchAllDatabaseData" object:self userInfo:nil];
});
});
return persistentStoreCoordinator;
}
- (void)mergeiCloudChanges:(NSNotification*)note forContext:(NSManagedObjectContext*)moc {
[moc mergeChangesFromContextDidSaveNotification:note];
NSNotification* refreshNotification = [NSNotification notificationWithName:#"RefreshAllViews" object:self userInfo:[note userInfo]];
[[NSNotificationCenter defaultCenter] postNotification:refreshNotification];
}
- (void)mergeChangesFrom_iCloud:(NSNotification *)notification {
NSManagedObjectContext* moc = [self managedObjectContext];
// this only works if you used NSMainQueueConcurrencyType
// otherwise use a dispatch_async back to the main thread yourself
[moc performBlock:^{
[self mergeiCloudChanges:notification forContext:moc];
}];
}
#pragma mark - Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
viewController.h
#import <Foundation/Foundation.h>
#import "CollectionViewController.h"
#import "SlideShowViewController.h"
#import "PagesDataSource.h"
#import "PageView.h"
#import "PageViewController.h"
#import "PrototypeView.h"
#import "QuickStart.h"
#interface PagesCollectionViewController : CollectionViewController<quickStartDismiss,NSFetchedResultsControllerDelegate>
{
PagesDataSource *dataSource;
PageViewController *viewController;
#private NSFetchedResultsController *fetchedResultsController__ ;
#private NSManagedObjectContext *managedObjectContext__;
}
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
- (IBAction)add:(id)sender;
-(void)setShadowAndColor;
-(void)playSlideShow;
#property (nonatomic, readwrite, assign) BOOL editMode;
#end
#interface PageView (CollectionViewItem)
- (void)setRepresentedObject:(PVPage *)representedObject;
- (PVPage *)representedObject;
-(void)didHoldItem;
-(void)duplicatePage;
#end
#interface PushController : UIViewController
{}
#end
#interface toolBar : UIToolbar
#end
viewController.m
#import "PagesCollectionViewController.h"
#import "PageFlipperAppDelegate.h"
#implementation toolBar
- (void)drawRect:(CGRect)rect {}
#end
#implementation PagesCollectionViewController
#synthesize editMode;
#synthesize fetchedResultsController=__fetchedResultsController;
#synthesize managedObjectContext=__managedObjectContext;
-(void)viewWillAppear:(BOOL)animated{
if (![[NSUserDefaults standardUserDefaults] integerForKey:#"integerKey"]) {
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"integerKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
QuickStart*stickieViewController = [[[QuickStart alloc]init]autorelease];
stickieViewController.delegate = self;
stickieViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:stickieViewController animated:YES];
}
[[self navigationController] setNavigationBarHidden:NO animated:NO];
[[self navigationController] setToolbarHidden:NO animated:NO];
[[[self navigationController] toolbar] setBarStyle:UIBarStyleBlackTranslucent];
[self setToolbarItems:[NSArray arrayWithObjects:
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:#selector(playSlideShow)]autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease],
nil]];
[(CollectionView*)[self view] setCanReloadData:YES];
[(CollectionView*)[self view]layoutSubviews];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil)
{
return __fetchedResultsController;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Page" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptorName = [[NSSortDescriptor alloc] initWithKey:#"<sort key>" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorName, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"<section name key path>" cacheName:#"<cache name>"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptorName release];
[sortDescriptors release];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
// because the app delegate now loads the NSPersistentStore into the NSPersistentStoreCoordinator asynchronously
// we will see the NSManagedObjectContext set up before any persistent stores are registered
// we will need to fetch again after the persistent store is loaded
- (void)reloadFetchedResults:(NSNotification*)note {
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (note) {
[(CollectionView*)[self view] setCanReloadData:YES];
[(CollectionView*)[self view]layoutSubviews];
}
}
-(void) playSlideShow{
SlideShowViewController *slideShowViewController = [[[SlideShowViewController alloc] init]autorelease];
NSMutableArray *tempArrayOfImages = [[[NSMutableArray alloc] init]autorelease];
for (int i = 0; i < [[dataSource pages]count]; i++) {
if ([[[dataSource pages] objectAtIndex:i] thumbnail] != nil) {
[tempArrayOfImages addObject: [[[dataSource pages] objectAtIndex:i] thumbnail]];
}
}
[[self navigationController] pushViewController:slideShowViewController animated:YES];
[slideShowViewController setImagesInImageViewer:tempArrayOfImages];
}
-(void)dismissQuickStart{
[self dismissModalViewControllerAnimated:YES];
}
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
if ((self = [super initWithNibName:#"CollectionView" bundle:nil]))
{
if (editMode == NO) {
[self finishEditToolBars];
}
[self setTitle:#"Doodles"];
viewController = [[PageViewController alloc] initWithManagedObjectContext:managedObjectContext];
dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:managedObjectContext];
CGSize itemViewMarginSize = CGSizeMake(25.0, 0.0);
[(CollectionView *)[self view] setItemViewMarginSize:itemViewMarginSize];
PrototypeView *pro = [[[PrototypeView alloc] init] autorelease];
[(CollectionView *)[self view] setItemViewPrototype:pro];
[(CollectionView *)[self view] setFlowDirection:CVFlowDirectionVertical];
[(CollectionView *)[self view] setItemViewFrameSize:CGSizeMake(([(CollectionView *)[self view] bounds].size.width - 3*itemViewMarginSize.width)/3.4, ([(CollectionView *)[self view] bounds].size.height - 3*itemViewMarginSize.height)/3.6)];
[self setShadowAndColor];
}
return self;
}
-(void)setShadowAndColor{
CollectionView *collectionView = (CollectionView *)[self view];
[collectionView setShadowColor:[UIColor blackColor]];
[collectionView setShadowRadius:6.0f];
[collectionView setShadowOpacity:0.5f];
}
- (void)add:(id)sender
{
[dataSource add:sender];
CollectionView *collectionView = (CollectionView *)[self view];
// [collectionView reloadData];
// [collectionView scrollItemIndexToVisible:[self countOfItemsInCollectionView:collectionView]-1 animated:NO];
[collectionView.dataDelegate collectionView:collectionView didSelectItemAtIndex:[self countOfItemsInCollectionView:collectionView]-1];
//CollectionViewController *c;
// [[c transitionToDetailViewController:[c collectionView:self detailViewControllerForItemAtIndex:(NSUInteger)[self countOfItemsInCollectionView:collectionView]-1] forItemView:[itemViews objectForKey:[NSString stringWithFormat:#"%u", [self countOfItemsInCollectionView:collectionView]-1]]]];
// [c transitionToDetailViewController:self forItemView:collectionView.itemViews;
editMode = NO;
//collectionView.canUpdateLayout = YES;
collectionView.canReloadData = YES;
[(CollectionView*)[self view]layoutSubviews];
}
- (NSUInteger)countOfItemsInCollectionView:(CollectionView *)collectionView { return [[dataSource pages] count]; }
- (id)collectionView:(CollectionView *)collectionView representedObjectAtIndex:(NSUInteger)itemIndex {
return [[dataSource pages] objectAtIndex:itemIndex];
}
- (void)collectionView:(CollectionView *)collectionView didSelectItemAtIndex:(NSUInteger)itemIndex
{
if (editMode == YES) {
[collectionView yellowdidSelectItemAtIndex:itemIndex];
// NSLog(#"edit");
}else{
PVPage *selectedPage = [[[dataSource pages] objectAtIndex:itemIndex]autorelease];
PageView *pageView = [[[PageView alloc] init] autorelease];
[pageView setRepresentedPage:selectedPage];
// UIImage *i = [UIImage imageWithData: [[pageView representedPage] thumbnail]];
// UIImageView *ii = [[[UIImageView alloc] initWithImage:i]autorelease];
[viewController setView:pageView];
// [(PageView*)[viewController view] setBackgroundStrokes:ii];
//NSLog(#"selected page %#",selectedPage);
// [[[self navigationController] toolbar] setHidden:YES];
// [[[self navigationController] navigationBar] setHidden:YES];
// [[[self tabBarController] tabBar] setHidden:YES];
PageFlipperAppDelegate *appDelegate = (PageFlipperAppDelegate *)[[UIApplication sharedApplication] delegate];
// [(UiWindowSubclass *)appDelegate.window startTimer];
[(UINavigationController *)[(UiWindowSubclass*)[appDelegate window] rootViewController] pushViewController:viewController animated:YES];
// viewController = nil;
// [[self navigationController] setToolbarHidden:NO];
}
}
- (BOOL)collectionView:(CollectionView *)collectionView canDeleteItemAtIndex:(NSUInteger)itemIndex {
NSLog(#"itemIndex %u",itemIndex);
return YES;
}
- (void)collectionView:(CollectionView *)collectionView didDeleteItemAtIndex:(NSUInteger)itemIndex
{
[dataSource removePageAtIndex:itemIndex];
}
-(void)trash{
// NSLog(#"trash");
[(CollectionView *)[self view] trashitems];
}
-(void)done{
[(CollectionView *)[self view] yellowdidSelectItemAtIndexUndo];
[(CollectionView *)[self view] shakedidRemoveSelectItemAtIndex];
[(CollectionView *)[self view] donereset];
[self finishEditToolBars];
}
-(void) finishEditToolBars{
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add:)] autorelease]];
[[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(didHoldItem)] autorelease]];
editMode = NO;
}
-(void)duplicatePage{
NSArray *tempArray = [[[(CollectionView*)[self view] selectedItemsArray]copy]autorelease];
// for (int i =0; i<[[(CollectionView*)[self view] selectedItemsArray]count]; i++) {
// [(CollectionView *)[self view] yellowdidSelectItemAtIndex:i];
//
// }
[dataSource duplicatePage:[[[NSArray alloc] initWithArray:tempArray]autorelease]];
CollectionView *collectionView = (CollectionView *)[self view];
editMode = NO;
[self done];
// [(CollectionView *)[self view] yellowdidSelectItemAtIndexUndo];
collectionView.canReloadData = YES;
[collectionView layoutSubviews];
}
-(void)didHoldItem{
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done)] autorelease]];
// [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:#selector(trash)] autorelease]];
toolBar* tools = [[toolBar alloc] initWithFrame:CGRectMake(0, 0, 133, 44.01)];
tools.barStyle = UIBarStyleBlackTranslucent;
tools.opaque = NO;
//tools.backgroundColor = [UIColor clearColor];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
// create a standard "add" button
UIBarButtonItem* bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:#selector(trash)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];
// create a spacer
bi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[buttons addObject:bi];
[bi release];
// create a standard "refresh" button
bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:#selector(duplicatePage)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];
// stick the buttons in the toolbar
[tools setItems:buttons animated:NO];
[buttons release];
// and put the toolbar in the nav bar
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];
[tools release];
[(CollectionView*)[self view] setOldItemIndex:-1];
editMode = YES;
[(CollectionView*)[self view] setEditMode:YES];
[(CollectionView*)[self view] shakedidSelectItemAtIndex];
}
-(void)didReceiveMemoryWarning{
// NSLog(#"mem");
}
- (void)dealloc
{ [dataSource release],dataSource = nil;
[viewController release],viewController = nil;
[super dealloc];
}
-(void)viewDidAppear:(BOOL)animated{
[ (CollectionView*) [self view] setCanReloadData:YES];
[(CollectionView*) [self view] layoutSubviews];
}
-(void) viewDidLoad{
CollectionView *collectionView = (CollectionView *)[self view];
collectionView.canReloadData = YES;
[(CollectionView*)[self view]layoutSubviews];
editMode = NO;
collectionView.editMode = NO;
}
#end
On the Apple developer forums the iPhoneCoreDataRecipes sample code is posted, which includes iCloud.
https://devforums.apple.com/thread/126670?tstart=0
You can watch this year's WWDC 2012 Session 227 lecture (you can freely access these videos using your Apple Developer account), that will show how to correctly use Core Data and iCloud together, illustrating the correct application architecture, the way Core Data and iCloud should talk to each other and explaining all this stuff through a complete sample project.
Edit
The full source of the project is only available to all registered Apple developers under this page.
This is a very controversial topic... I need to add iCloud with Core Data in my next application but it's a bit hard to start. I have done nothing but I found these documents very useful:
Using Core Data with iCloud Release Notes
Using iCloud in Conjunction with Databases
Your Third iOS App: iCloud
It's not just controversial, it's not working adequately yet. If you are able to code the sample, you'll likely find that it only works on occasion. I wish I could write that it's solved and here is how you use it - maybe someone else can, but as of March 2012, I doubt it.
Still, it's interesting and instructive to code the sample, and the others in the dev site, so that you can learn what iCloud/core data is all about.
A lot of us are chomping at the bit for this to solidify.
You may want to try Dox from Ray Wenderlich's fantastic site. But you'll likely end up with the same frustration. Sometimes it works, mostly not.
Blackpixel have upped a version of Core Data Recipes with iCloud to Github. It may have improvements over the version in the dev forums.
I've used the dev forums version and found that it works, but takes some time to sync. Read the comments thread there (19 pages and counting) and make up your mind about it.
Actually I am Making an Alarm app. In that When i set the Time The UILocalNotification event happens at that time and it calls the method of AppDelegate class i.e didReceiveNotifications method. In this method i have written a code to call a method of SetViewController (showReminder method) and now in this method i want that it should show a NewViewController i.e TimeViewController as i have to show animation when the Alarm Invokes.
I need this as When Alarm invokes i have setted a Action sheet to appear but i wanted to show animation also.Action sheet appears in all views But the animation can be Shown in only particular view, that's why i need to show A different ViewController.
Here is the code for what i am trying :-
I have tried al these also like PresentModalViewController, dismissModalViewController, AddSubview, remove superView... but result are negative :( what should i do..?
Almost Whole CODE:--
AppDelegate Class :-
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (notification){
NSLog(#"In did Notification");
NSString *reminderText = [notification.userInfo objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
application.applicationIconBadgeNumber = 0;
}
}
setViewController.h :-
#interface SetAlarmViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIActionSheetDelegate>{
IBOutlet UITableView *tableview;
IBOutlet UIDatePicker *datePicker;
IBOutlet UITextField *eventText;
TPKeyboardAvoidingScrollView *scrollView;
IBOutlet UINavigationBar *titleBar;
IBOutlet UIButton *setAlarmButton;
AVAudioPlayer *player;
int index;
The420DudeAppDelegate *appDelegate;
TimeViewController *viewController;
IBOutlet UIImageView *animatedImages;
NSMutableArray *imageArray;
AVPlayerItem *player1,*player3;
AVPlayerItem *player2,*player4;
AVQueuePlayer *queuePlayer;
}
#property (nonatomic, retain) IBOutlet UIImageView *animatedImages;
#property (nonatomic, retain) IBOutlet UITableView *tableview;
#property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
#property (nonatomic, retain) IBOutlet UITextField *eventText;
#property (nonatomic, retain) TPKeyboardAvoidingScrollView *scrollView;
#property(nonatomic, retain) IBOutlet UINavigationBar *titleBar;
#property(nonatomic, retain) IBOutlet UIButton *setAlarmButton;
#property(nonatomic) UIReturnKeyType returnKeyType;
#property(nonatomic, retain) IBOutlet TimeViewController *viewController;
- (IBAction) scheduleAlarm:(id)sender;
- (void)showReminder:(NSString *)text;
-(IBAction)onTapHome;
-(IBAction)onTapChange:(id)sender;
#end
SetViewController.m :-
#synthesize datePicker,tableview, eventText,titleBar,setAlarmButton,returnKeyType,scrollView,animatedImages,viewController;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (The420DudeAppDelegate *)[[UIApplication sharedApplication] delegate];
eventText.returnKeyType = UIReturnKeyDone;
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
NSDate *now = [NSDate date];
[datePicker setDate:now animated:YES];
eventText.delegate = self;
index = 0;
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"inhale" ofType:#"mp3"];
NSURL *url1 = [NSURL fileURLWithPath:path1];
player1 = [[AVPlayerItem alloc]initWithURL:url1];
NSString *path3 = [[NSBundle mainBundle] pathForResource:#"sound1" ofType:#"wav"];
NSURL *url3 = [NSURL fileURLWithPath:path3];
player3 = [[AVPlayerItem alloc]initWithURL:url3];
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"exhale" ofType:#"mp3"];
NSURL *url2 = [NSURL fileURLWithPath:path2];
player2 = [[AVPlayerItem alloc]initWithURL:url2];
NSString *path4 = [[NSBundle mainBundle] pathForResource:#"Dude" ofType:#"mp3"];
NSURL *url4 = [NSURL fileURLWithPath:path4];
player4 = [[AVPlayerItem alloc]initWithURL:url4];
NSArray *items = [[NSArray alloc]initWithObjects:player1,player3,player2,player4,nil];
queuePlayer = [[AVQueuePlayer alloc] initWithItems:items];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playEnded) name:AVPlayerItemDidPlayToEndTimeNotification object:player4];
}
-(void)onAlarmInvoke
{
animatedImages = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
animatedImages.userInteractionEnabled = YES;
[animatedImages setContentMode:UIViewContentModeScaleToFill];
[self.view addSubview : animatedImages];
[queuePlayer play];
// Array to hold jpg images
imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];
// Build array of images, cycling through image names
for (int i = 1; i <= IMAGE_COUNT; i++)
[imageArray addObject:[UIImage imageNamed:[NSString stringWithFormat:#"animation(%d).jpg", i]]];
animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
// One cycle through all the images takes 1.0 seconds
animatedImages.animationDuration = 12.0;
// Repeat foreverlight electro / 4 sec.
animatedImages.animationRepeatCount = -1;
// Add subview and make window visible
// [self.view addSubview:animatedImages];
animatedImages.image = [imageArray objectAtIndex:imageArray.count - 1];
// Start it up
[animatedImages startAnimating];
// Wait 5 seconds, then stop animation
[self performSelector:#selector(stopAnimation) withObject:nil afterDelay:15000];
}
-(void)playEnded
{
[self performSelector:#selector(playNextItem) withObject:nil afterDelay:5.0];
}
-(void)playNextItem
{
[queuePlayer play];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[scrollView adjustOffsetToIdealIfNeeded];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
[self.tableview reloadData];
}
- (IBAction) scheduleAlarm:(id)sender {
[eventText resignFirstResponder];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// NSDate *selectedDate = [datePicker date]; // you don't need to alloc-init the variable first
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dc = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:pickerDate];
pickerDate = [cal dateFromComponents:dc];
NSLog(#"%# is the date in picker date",pickerDate);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = pickerDate;
// NSLog(#"%#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// NSLog(#"%#",localNotif.timeZone);
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = #"Show me";
localNotif.repeatInterval = NSDayCalendarUnit;
localNotif.soundName = #"jet.wav";
// Specify custom data for the notification
NSDictionary *userDict = [NSDictionary dictionaryWithObject:eventText.text
forKey:kRemindMeNotificationDataKey];
localNotif.userInfo = userDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[self.tableview reloadData];
eventText.text = #"";
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
index = indexPath.row;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Warning!!!"
message:#"Are you sure you want to Delete???" delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok",nil];
[alertView show];
[alertView release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notify = [notificationArray objectAtIndex:index];
if(buttonIndex == 0)
{
// Do Nothing on Tapping Cancel...
}
if(buttonIndex ==1)
{
if(notify)
[[UIApplication sharedApplication] cancelLocalNotification:notify];
}
[self.tableview reloadData];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];
return cell;
}
- (void)viewDidUnload {
datePicker = nil;
tableview = nil;
eventText = nil;
[self setScrollView:nil];
[super viewDidUnload];
}
- (void)showReminder:(NSString *)text {
[self onAlarmInvoke];
[self.view addSubview:viewController.view];
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:#"Cancel" otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect rect = self.view.frame;
// if(rect.origin.y <= 480)
// rect.origin.y +=20;
self.view.frame = rect;
[actionSheet showInView:self.view];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
[player stop];
NSLog(#"OK Tapped");
}
if(buttonIndex == 1)
{
[player stop];
NSLog(#"Cancel Tapped");
}
}
-(IBAction)onTapHome{
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
- (void)dealloc {
[super dealloc];
[datePicker release];
[tableview release];
[eventText release];
[scrollView release];
}
-(IBAction)onTapChange:(id)sender{
SetTimeViewController *viewC = [[SetTimeViewController alloc]initWithNibName:#"SetTimeViewController" bundle:nil];
[self presentModalViewController:viewC animated:YES];
}
#end
Your viewController is probably showing the view, but without the SetViewController's view on the screen you can't see it. Your going to have to first go to the SetViewController and then present your TimeViewController. Is this right, you want to show the SetViewController but call the showReminder: method right away? But only from the didReceiveLocalNotification:.
If this is the case, set a flag,and a text property in your SetViewControllers .h,
BOOL isFromNotification;
NSString *notifText;
and present the SetViewController,and set the flag
SetViewController *setViewController = [SetViewController alloc]........
setViewController.isFromNotification = YES;
setViewController.notifText = reminderText;
[self presentModalViewController animated:YES}
and then in the viewDidAppear: of SetViewController
if(isFromNotification = YES){
[self showReminders:notifText];
}
If I got you right ,
upon notification you would like to show animation on a new view and then show the action sheet ?
Right now you call from appdelegate
[viewController showReminder:reminderText];
which by the way should be self.viewcontroller or _viewcontroller for the actually retained object
In showreminder you call
animation, which in itself adds a subview and by the way is running in the same thread , ie in serial.
and then you add the viewcontroller again as a subview.
and then you try to add the actionsheet from parent to the subview(viewcontroller), when actionsheet should probably be in the viewcontroller itself.
Did i get that right ?
No sure really whats breaking down, could be on several areas, as pointed out above.
I would :
make sure you call the retained objects through valid pointers ( using self for instance)
have a viewcontroller that you present modal as a subview that show animations on a separate thread (performselectoronthread) and have the actionsheet on that.
Then if you need to call the parent, you setup a delegate or you do the ugly way.
self.yourviewcontroller.myParentObj = self
ie set a yourviewcontroller pointer on the sub viewcontroller, which you can then openly call like
[self.myParentObj whatevermethod_you_have_in_parent];
But then again I write this from top of my head..
i will like to know how do i call didFinishLaunchingWithOptions again after in app updates download, as all my function calling are in there.
i need to call this again self.dataArray = [self readDataJsonFromDocument];again as i download data from the net.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self UIAppearances];
//first load
[self copyJsonFromBundle];
[self copyFolderFromBundle];
self.dataArray = [self readDataJsonFromDocument]; //i need to call this again
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *downloadFolder = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"download"];
//save to a temp file
NSString* filePath = [NSString stringWithFormat:#"%#/temp.zip", self.documentsDir];
//download folder
//NSString* downloadFolder = [NSString stringWithFormat:#"%#/download", self.documentsDir];
[self.fileManager createFileAtPath:filePath contents:self.receivedData attributes:nil];
ZipArchive *zipArchive = [[ZipArchive alloc] init];
if([zipArchive UnzipOpenFile:filePath]) {
// if ([zipArchive UnzipFileTo:downloadFolder overWrite:YES]) {
if ([zipArchive UnzipFileTo:self.documentsDir overWrite:YES]) {
//unzipped successfully
NSLog(#"Archive unzip Success");
[self.fileManager removeItemAtPath:filePath error:NULL];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
} else {
NSLog(#"Failure To Unzip Archive");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
} else {
NSLog(#"Failure To Open Archive");
}
//[self performSelectorOnMainThread:#selector(didUpdate) withObject:nil waitUntilDone:YES];
//Update Document File
NSString *updateUTCPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"UTCDate"];
NSDate *currentDate = [NSDate date];
NSArray *array = [NSArray arrayWithObject:currentDate];
[array writeToFile:updateUTCPath atomically:YES];
}
what are you trying to do?
You can certainly manually call your App Delegate's didFinishLaunchingWithOptions method a second time, but it would probably make more sense to put all the functionality you want to be done a second time into a separate function that gets called by both the delegate that's attached to your download updates method and the didFinishLaunchingWithOptions method.
You should abstract your code into another method and call that method. You shouldn't call UIApplicationDelegate methods directly.
In my iphone application an activity indicator is shown at the time of webservice call. My problem is that i am able to touch the view on which the activity indicator is shown.My view has textfields and buttons and i am able to enter values in the text fields and also change the button states while the activity indicator is still on it. Have anybody faced a similar situation? Does anybody know a solution to this problem? All helpful suggestions are welcomed.
Here is my activity indicator class.
ActivityProgressViewController.h
#import <UIKit/UIKit.h>
#interface ActivityProgressViewController : UIViewController {
IBOutlet UIActivityIndicatorView *_activityIndicator;
IBOutlet UILabel *_labelMessage;
NSString *_messageToShow;
}
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *activityIndicator;
#property (nonatomic, retain) IBOutlet UILabel *labelMessage;
+ (ActivityProgressViewController*) createInstance;
- (void)show;
- (void)showWithMessage:(NSString*)message;
- (void)close;
+ (void)show;
+ (void)close;
#end
ActivityProgressViewController.m
#import "ActivityProgressViewController.h"
#define kACTIVITY_INDICATOR_NIB #"ActivityProgressViewController"
#implementation ActivityProgressViewController
#synthesize activityIndicator = _activityIndicator;
#synthesize labelMessage = _labelMessage;
static ActivityProgressViewController *_viewController;
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad {
if (_messageToShow) _labelMessage.text = _messageToShow;
}
- (void)dealloc {
[_labelMessage release];
[_messageToShow release];
[_activityIndicator release];
[super dealloc];
}
+ (ActivityProgressViewController*) createInstance {
_viewController = [[ActivityProgressViewController alloc] initWithNibName:kACTIVITY_INDICATOR_NIB bundle:nil];
return _viewController;
}
- (void)show
{
[_activityIndicator startAnimating];
UIWindow *window = [[[UIApplication sharedApplication] windows]objectAtIndex:0];
NSLog(#"[[UIApplication sharedApplication] windows]===%#",[[UIApplication sharedApplication] windows]);
self.view.frame = CGRectMake(window.bounds.origin.x, window.bounds.origin.y, window.bounds.size.width, window.bounds.size.height);
[window addSubview:self.view];
}
- (void)showWithMessage:(NSString*)message {
_messageToShow = message;
[self show];
}
- (void)close
{
[self.view removeFromSuperview];
}
+ (void)show {
if (!_viewController) {
_viewController = [ActivityProgressViewController createInstance];
}
[_viewController show];
}
+ (void)close {
if (_viewController) {
[_viewController close];
}
}
#end
Here is how i call from my required class.
[ActivityProgressViewController show];
[ActivityProgressViewController close];
I also call the activity indicator while exporting audio.
This is the code I use for exporting
-(void)exportAudioFile:(AVComposition*)combinedComposition
{
[ActivityProgressViewController show];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:combinedComposition
presetName:AVAssetExportPresetPassthrough];
NSArray *presets =[AVAssetExportSession exportPresetsCompatibleWithAsset:combinedComposition];
NSLog(#"presets======%#",presets);
NSLog (#"can export: %#", exportSession.supportedFileTypes);
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
exportPath = [documentsDirectoryPath stringByAppendingPathComponent:#"CombinedNew.m4a"];
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = exportURL;
exportSession.outputFileType = #"com.apple.m4a-audio";
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSLog (#"i is in your block, exportin. status is %d",
exportSession.status);
switch (exportSession.status)
{
case AVAssetExportSessionStatusFailed:
{
break;
}
case AVAssetExportSessionStatusCompleted:
{
exportSuccess = YES;
if (recorderFilePath)
{
NSError *finalurlError;
[[NSFileManager defaultManager]removeItemAtPath:recorderFilePath error:&finalurlError];
finalurlError = nil;
[[NSFileManager defaultManager]copyItemAtPath:[exportURL path] toPath:recorderFilePath error:&finalurlError];
NSLog(#"finalurlError 2-----%#",finalurlError);
}
[ActivityProgressViewController close];
fileUrl = [NSURL fileURLWithPath:recorderFilePath];
[self updatePlayerForUrl:fileUrl];
break;
}
case AVAssetExportSessionStatusUnknown:
{
break;
}
case AVAssetExportSessionStatusExporting:
{
break;
}
case AVAssetExportSessionStatusCancelled:
{
break;
}
case AVAssetExportSessionStatusWaiting:
{
break;
}
default:
{
NSLog (#"didn't get export status");
break;
}
};
}];
[exportSession release];
}
You're adding your activity indicator to the middle of another view, yes?
If so, you can do this in your show method:
self.superview.userInteractionEnabled = NO;
And in your close method:
self.superview.userInteractionEnabled = YES;
Here is where you'll find information on the UIView's userInteractionEnabled property: http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instp/UIView/userInteractionEnabled
Hope this helps!