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.
Related
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.
I am updating my app to use iCloud and want my iOS deployment target to remain 3.2. I am conditionally shielding any iOS 5 calls to prevent any back level versions from crashing. My applicationDidFinishLaunching looks like...
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSLog(#"Launching Began...");
navigationController = [[UINavigationController alloc] init];
navigationController.navigationBar.barStyle = UIBarStyleBlack;
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
// Getting the documentsPath.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
// Setting up the mainCarList
//unarchive the saved carlist
NSString *archivePathFilename = [documentsPath stringByAppendingString:#"/carlist.archive"];
self.mainCarList = nil;
self.mainCarList = [[NSKeyedUnarchiver unarchiveObjectWithFile:archivePathFilename] retain];
//if OS version => 5.0 then
NSString *reqSysVer = #"5.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
NSLog(#"in ApplicationDidFinishLaunching iOS version > 5.0");
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(carListDocumentStateChanged) name:#"UIDocumentStateChangedNotification" object:Nil];
NSString *carListDocumentURLString = [documentsPath stringByAppendingString:#"/mainCarListDocument.CLD"];
self.mainCarListDocumentURL = [NSURL fileURLWithPath:carListDocumentURLString]; //sets the local save location only in this property
Class cls = NSClassFromString (#"NSMetadataQuery");
if (cls) {
NSMetadataQuery *query;
query = [[NSMetadataQuery alloc] init]; // <------- This crashes when running v4.3 iPhone sim.
/*
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
[self setDocumentMetaDataQuery:query];
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDataScope]];
[query setPredicate:[NSPredicate predicateWithFormat:#"%K == %#", NSMetadataItemFSNameKey, #"mainCarListDocument.CLD"]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryDidFinishGathering) name:NSMetadataQueryDidFinishGatheringNotification object:Nil];
BOOL didStart = NO;
didStart = [query startQuery];
if (didStart) {
NSLog(#"documentMetaDataQuery started");
}
else {
NSLog(#"error starting documentMetaDataQuery");
}
*/
[query release];
}
...
I think something is going on at compile time since the "Launching Began" log is not posted. The conditional block works correctly. If I comment out the query's alloc init, then the block gets ran only if iOS 5 is running. Any ideas?
Replace the following code:
NSMetadataQuery *query;
query = [[NSMetadataQuery alloc] init];
By this code:
id query;
query = [[cls alloc] init];
You have to use cls instead of NSMetadataQuery.
I've tried everything I can think of and it still responds NO and Apple's doesn't have any hints.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"finished!");
NSString *tempString = [NSString stringWithFormat:#"file://%#%#", NSTemporaryDirectory(), [[NSProcessInfo processInfo] globallyUniqueString]];
NSURL *tempURL = [NSURL URLWithString:tempString];
[receivedData writeToURL:tempURL atomically:YES];
NSLog(#"tempURL is written!");
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL:tempURL];
interactionController.delegate = self;
[interactionController retain];
NSLog(#"--- %i", [interactionController presentPreviewAnimated:YES]);
NSLog(#"presented preview");
[connection release];
[receivedData release];
}
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
NSLog(#"asdf");
UIViewController *viewController = [[[UIViewController alloc] init] autorelease];
[self.navigationController pushViewController:viewController animated:YES];
return viewController;
}
1) are you confident the document you're opening is kosher? If not, then returning NO would be the thing to expect
2) I'm puzzled by your delegate method. The present method is happy to do the pushing onto the navigation controller all by itself. Do you fair any better if you use this code instead? (See the docs for rationale.)
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller
{
return [self navigationController];
}
I had a similar issue with presentPreviewAnimated which returned NO. In my case I was missing an extension of the file. When I renamed my file from document to document.xlsx it was opened successfully.
I am created an application which play multiple audio files from locally. Audio files are long. Audio player has following options for the user
Forward,
Rewind,
Next Track,
Previous Track,
I am planning to use AvAudioPlayer so that i can play an audio with long time. When i am changing the audio file ie pressing next track audio. The audioplayer instance is not getting released. This problem is appearing some times only. Please help me..!! I am help less..
Next Track Button IBAction Method
- (IBAction) nextTrackPressed
{
[audioPlay stopAudio];
if (audioPlay) {
audioPlay = nil;
[audioPlay release];
}
appDelegate.trackSelected += 1;
[self intiNewAudioFile];
[self play];
}
Initializing audio file through below method
-(void) intiNewAudioFile
{
NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
NSString *filePath = [[NSString alloc] init];
trackObject = [appDelegate.trackDetailArray objectAtIndex:appDelegate.trackSelected];
NSLog(#"%#",trackObject.trackName);
// Get the file path to the song to play.
filePath = [[NSBundle mainBundle] pathForResource:trackObject.trackName ofType:#"mp3"];
// Convert the file path to a URL.
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
if (audioPlay) {
audioPlay = nil;
[audioPlay release];
}
audioPlay = [[AudioPlayerClass alloc] init];
[audioPlay initAudioWithUrl:fileURL];
[filePath release];
[fileURL release];
[subPool release];
}
AudioPlayerClass Implementation
#import "AudioPlayerClass.h"
#implementation AudioPlayerClass
- (void) initAudioWithUrl: (NSURL *) url
{
curAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[curAudioPlayer setDelegate:self];
[curAudioPlayer prepareToPlay];
}
- (void) playAudio
{
[curAudioPlayer play];
}
- (void) pauseAudio
{
[curAudioPlayer pause];
}
- (void) stopAudio
{
[curAudioPlayer stop];
}
- (BOOL) isAudioPlaying
{
return curAudioPlayer.playing;
}
- (void) setAudiowithCurrentTime:(NSInteger) time
{
curAudioPlayer.currentTime = time;
}
- (NSInteger) getAudioFileDuration
{
return curAudioPlayer.duration;
}
- (NSInteger) getAudioCurrentTime
{
return curAudioPlayer.currentTime;
}
- (void) releasePlayer
{
[curAudioPlayer release];
}
- (void)dealloc {
[curAudioPlayer release];
[super dealloc];
}
#end
Your problem is here:
if (audioPlay) {
audioPlay = nil;
[audioPlay release];
}
You are setting audioPlay to nil before calling release which means that the release message is getting sent to nil. You need to reverse the order of these 2 lines.
if (audioPlay) {
[audioPlay release];
audioPlay = nil;
}
The plist has the file suffix .xml and is a normal array of dictionaries.
In the app delegate:
#define docDir [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
-(NSString *)cacheFile:(NSString *)filename sitepath:(NSString *)url {
NSMutableString *retfn=[NSMutableString string];
NSString *mediaUrl=[NSString stringWithFormat:#"%#%#",url,filename];
if(nil != mediaUrl){
NSData* imageData;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
#try {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
}
#catch (NSException * e) { //error
NSLog(#"%#",#"CacheFile error!");
}
#finally { //save to Documents
[retfn appendFormat:#"%#%#%#",docDir,#"/",filename];
[imageData writeToFile:retfn atomically:YES];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[imageData release];
}
return retfn;
}
In my tableView controller:
#define fname #"myplist.xml"
#define fdir #"http://mysite.com/iPhoneApp/"
- (void)viewDidLoad {
appdel=(EksjoHusAppDelegate *) [[UIApplication sharedApplication] delegate];
NSString *husDataF=[appdel cacheFile:fname sitepath:fdir];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:husDataF];
if (([husDataF length]>0)&&(fileExists)) {
NSMutableArray *lochusData=[[NSMutableArray alloc] initWithContentsOfFile:husDataF];
appdel.husData=lochusData;
[lochusData release];
}
}
initWithContentsOfFile sets lochusData to 0x0. This the part of code I'm asking about, really. The rest is more for completion. cacheFile returns the local filepath or an empty string. All the values are correct, but it just won't load / go into the array.
Feeling dumb. I just don't see the error. Is there something I'm missing?
Answer was, "Check your charset when saving the generated XML, dude" :)