I would like to save an NSArray to NSUSerDefaults. If I do it on Simulator everything works, if I do it on Device, it doesnt work.
NSArray *Test1 = [Daten copy];
NSArray *Test2 = [Kosten copy];
[prefs setObject:Test1 forKey:#"Daten"];
[prefs setObject:Test2 forKey:#"Kosten"];
I am using the above code.
prefs is a normal NSUserDefaults, like NSUserDefaults *prefs = [NSUserDefaults standartUserDefaults];...
Daten & Kosten are Mutable Arrays, to work with.
Everything works on simulator, but on device it doesnt work...
Does anybody have an idea?
Are you synchronizing them after settings/updating ?
[[NSUserDefaults standardUserDefaults] synchronize];
Because Saurabh asked me to post my solution, I will do it for other readers.
My Problem Code was the following:
[derText1 resignFirstResponder]
[derText2 resignFirstResponder]
NSArray *Test1 = [Daten copy];
NSArray *Test2 = [Kosten copy];
[prefs setObject:Test1 forKey:#"Daten"];
[prefs setObject:Test2 forKey:#"Kosten"];
This worked on an iPhone 4 Simulator with XCode 3.2.5 but not on my Device with iOS 5.x installed.
So I have downloaded and installed the newest XCode version from Apple.
After that it also doesnt work with the Simulator too. It looks like the problem is only with iOS 5 Software.
Than I changed my code simply to that:
NSArray *Test1 = [Daten copy];
NSArray *Test2 = [Kosten copy];
[prefs setObject:Test1 forKey:#"Daten"];
[prefs setObject:Test2 forKey:#"Kosten"];
[derText1 resignFirstResponder]
[derText2 resignFirstResponder]
And it worked on Device and Simulator with the latest iOS. Take a look at the position of the resign First Responder Entrys. They seem to have to be after the saving. I don't know why, but it works.
NSArray *Test1 = [Daten copy];<p>
NSArray *Test2 = [Kosten copy];<p>
NSUserDefaults *prefs;<p>
prefs= [[NSUserDefaults standardUserDefaults]setObject:Test1 forKey:#"Daten"];<p>
[[NSUserDefaults standardUserDefaults] synchronize];
prefs= [[NSUserDefaults standardUserDefaults]setObject:Test2 forKey:#"Kosten"];<p>
[[NSUserDefaults standardUserDefaults] synchronize];
Related
I've written code like this
NSString *path = [[NSBundle mainBundle] pathForResource:#"iOS app development " ofType:#"mp4"];
NSLog(#" path %#",path);
NSURL *url = [NSURL fileURLWithPath:path] ;
movie1 = [QTMovie movieWithURL:url error:nil];
[Movieview setMovie:movie1];
[[Movieview movie]play];
when i run application only audio is playing. if any one know the answer please help me
thank you.
Add
[[movie1 window] makeKeyAndOrderFront:self];
It should fix your problem
I am new to iOS and trying to add sound to my app. I have followed several tutorials about adding a simple sound file to my project, but ALL with the same result. I get no errors, but no sound plays. Any ideas on what I am doing wrong? Any help would be appreciated!
- (IBAction)playSound:(id)sender {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(soundFilePath);
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
player.numberOfLoops = 1;
[player play];
}
**UPDATE***
So I never had any luck with the above code which is very discouraging, but I did end up getting it to work using the AudioToolbox Framework instead, using this:
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle]
pathForResource:#"test" ofType:#"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)
[NSURL fileURLWithPath:soundFile], & soundID);
AudioServicesPlaySystemSound(soundID);
Can anyone explain to me the difference, why this one works and the other does not?? I am curious more than anything. Would love some clarification.
Finally figured it out. I needed to create a property for AVAudioPlayer in my header file in order to get it to work. Here is what I did:
// .h file
#interface ThirdViewController : UIViewController {
AVAudioPlayer *audioPlayer;
}
#property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (void) playSound //method in .m file
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"test"
ofType:#"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer play];
}
Simplify your code by doing the follow. Also drop your test.mp3 to the root of your project directory in xcode. Your mp3 placement and location is very important. Also ensure volume is up, and vibrate is off of your device, and it's unmuted.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"test"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:nil];
[audioPlayer play];
Make sure you install quartz.h, or a specific framework that supports audio players. Just double check.
Had the same problem a while back and the framework must be installed properly.
I'm trying to play a looped sound file one time, each time the app is opened. I'm doing this because I currently have the code in the viewDidLoad of my initial viewController. The problem was that each time I'd switch views and then go back to the initial view controller, it would play the sound file again and the sounds would overlap and it just sounded awful. I've posted my code below. Any help is much appreciated, thanks in advance!
{
if (![[NSUserDefaults standardUserDefaults]
boolForKey:#"loadSongOnce"]) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"Cartoon Sound" ofType:#"mp3"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.numberOfLoops = -1;
[theAudio play];
[[NSUserDefaults standardUserDefaults] setBool:YES
forKey:#"loadSongOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
Try this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
//self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
// self.window.rootViewController = self.viewController;
// [self.window makeKeyAndVisible];
if(![[[NSUserDefaults standardUserDefaults] valueForKey:#"firstTime"] isEqualToString:#"Yes"])
{
[[NSUserDefaults standardUserDefaults] setValue:#"Yes" forKey:#"firstTime"];
[[NSUserDefaults standardUserDefaults] setInteger:([[NSUserDefaults standardUserDefaults] integerForKey:#"ApplaunchCount"] + 1) forKey:#"ApplaunchCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else
{
[[NSUserDefaults standardUserDefaults] setInteger:([[NSUserDefaults standardUserDefaults] integerForKey:#"ApplaunchCount"] + 1) forKey:#"ApplaunchCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
if([[NSUserDefaults standardUserDefaults] integerForKey:#"ApplaunchCount"] % 1 ==0)
{
//Play sound file here
}
}
return YES;}
This shows that every time the app is killed (closed is multitasking), it will restart the sound. Let me know if this works, and just as before if not let me know!
Well what you would need to do is determine weather this is the first time loading the app or not. We would need to store this data as NSUserDefaults, because it is easy and simple.
-(BOOL)application:(UIApplication *)application … {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
// display alert...
[defaults setBool:YES forKey:#"notFirstRun"];
}
// rest of initialization ...}
Basically this tells the app if this is the first time loading the app, (play sound, you add that) and if not (don't play sound). After the sound is played, the bool will know it should change to YES and it will not run again, until you reload the app. When you go back to the view, that is where the if statement comes into play to tell the app that YES you already played the sound, and to not play it again!
Let me know if this works, and if not I will see what I can do!
I'm building an application that has a feature to open newly taken screenshots. I would like to distribute it using the Mac App Store. Unfortunately, it needs to be sandboxed.
To find the new screenshots I run a NSMetaDataQuery. It returns a few entries but unfortunately I can't get their URL since they are on the Desktop (out of my app's sandbox).
How can I fix this ?
Here is some of the code
query = [[NSMetadataQuery alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryUpdated:) name:NSMetadataQueryDidStartGatheringNotification object:query];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryUpdated:) name:NSMetadataQueryDidUpdateNotification object:query];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryUpdated:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query setDelegate:self];
[query setPredicate:[NSPredicate predicateWithFormat:#"kMDItemIsScreenCapture = 1"]];
[query startQuery];
numberOfScreenshots = [query resultCount];
[self uploadToAmazonS3:[[[query results]objectAtIndex:([query resultCount]-1)]valueForAttribute:NSMetadataItemURLKey]];
Thanks
Without asking user permission, you can access only Music, Movies, Pictures and Download folders.
You have to ask user, to grant you access to Desktop Folder. Then use mechanism called Security-Scoped Bookmarks, read more about it in AppSandboxDesignGuide.
Use NSOpenPanel to choose directory.
Save bookmark for future use, for example in NSUserDefaults.
Get access
1 and 2
NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
[openPanel setCanChooseFiles:NO];
[openPanel setCanChooseDirectories:YES];
[openPanel setCanCreateDirectories:YES];
[openPanel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
for (NSURL *fileURL in [openPanel URLs]) {
NSString *filename = [fileURL path];
[[NSUserDefaults standardUserDefaults] setObject:filename forKey:#"PathToFolder"];
NSError *error = nil;
NSData *bookmark = [fileURL bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys:nil
relativeToURL:nil
error:&error];
if (error) {
NSLog(#"Error creating bookmark for URL (%#): %#", fileURL, error);
[NSApp presentError:error];
} else {
[[NSUserDefaults standardUserDefaults] setObject:bookmark forKey:#"PathToFolder"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
break;
}
}
}];
3.
NSError *error = nil;
NSData *bookmark = [[NSUserDefaults standardUserDefaults] objectForKey:#"PathToFolder"];
bookmarkedURL = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:&error];
BOOL ok = [bookmarkedURL startAccessingSecurityScopedResource];
NSLog(#"Accessed ok: %d %#", ok, [bookmarkedURL relativePath]);
So, that sould be it.
After you have allowed access you also need to get the path to the real home folder - all the other file APIs only provide the path to the sandboxed folder even when access to the real one as been enabled. To get around this annoying problem, Apple recommend doing this to get the real home folder:
#include <sys/types.h>
#include <pwd.h>
const char *home = getpwuid(getuid())->pw_dir;
NSString *path = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation:home
length:strlen(home)];
NSString *realHomeDirectory = [[NSURL fileURLWithPath:path isDirectory:YES] path];
I'm working on a tiny project for LEOPARD (10.5) and I'm kinda rookie with Objective-C programming. I've been searching for some tutorials on internet but I'm still confused! I need to use Leopard's spotlight feature to search for every .app file installed at the user's computer. I also need its name, path and icon. All queried data must be saved in a text file. How can I do that???
Thank you!
Define the query, and observe the query termination.
- (void)searchApplications {
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
query.predicate = [NSPredicate predicateWithFormat:#"kMDItemContentTypeTree == 'com.apple.application'"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(queryDidFinish:)
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
[query startQuery];
}
In the query termination function, loop through the results and extract the data you want.
- (void)queryDidFinish:(NSNotification *)notification {
NSMetadataQuery *query = (NSMetadataQuery *)[notification object];
[query stopQuery];
NSMutableArray *paths = [NSMutableArray array];
for(NSMetadataItem *mdItem in query.results) {
NSString *name = [mdItem valueForAttribute:(NSString *)kMDItemDisplayName];
NSString *path = [mdItem valueForAttribute:(NSString *)kMDItemPath];
NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:path];
[paths addObject:path];
}
[query release];
[paths writeToFile:#"/tmp/applications.txt" atomically:YES];
}