Save Array to plist - xcode

I'm trying to store some items into a pList. Here is the array loop:
for (id obj in items)
NSLog(#"obj: %#", obj);
Output NSLog:
2013-03-27 13:00:40.072 mycode[47436:c07] obj: Red
2013-03-27 13:00:40.073 mycode[47436:c07] obj: Blue
2013-03-27 13:00:40.073 mycode[47436:c07] obj: Green
// The arrayWithObjects works. But I don't know how to (loop?) through my items for saving into the plist file...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: path]) {
NSLog(#"%#", path);
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
newArray = [NSArray arrayWithObjects:#"Red", #"Green", #"Blue" nil]; // <--- WORKS!
newArray = [NSArray arrayWithObjects:items, nil]; // <-- ?
[plist setObject:newArray forKey:#"Hi"];
[plist writeToFile:path atomically:YES];
[plist release];
} else {
NSLog(#"File not found");
}
[filemgr release];

Maybe this piece of code helps you.
NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *targetArray = [[[NSMutableArray alloc] init] autorelease];
newArray = [NSArray arrayWithObjects:#"Red", #"Green", #"Blue" nil];
for(int i=0;i<newArray.count;i++)
{
[targetArray addObject:[newArray objectAtIndex:i]];
}
[plist setObject:targetArray forKey:#"Hi"];
[plist writeToFile:path atomically:YES];
or another method
NSMutableArray *targetArray = [[[NSMutableArray alloc] init] autorelease];
for (id obj in items)
{
[targetArray addObject:items];
}
[plist setObject:targetArray forKey:#"Hi"];
[plist writeToFile:path atomically:YES];
Hope this helps !!!

Related

Objective c simple sorting using NSSortDescriptor

I want to simple sorting in nslog , this is my viewcontroller.
- (void)viewDidLoad {
[super viewDidLoad];
sobj=[[SortObjects alloc]init];
sobj.description; //this doesn't work
[sobj description];//this doesn't work either
NSLog(#"sobj = %#", sobj);
}`
& here is my Object Class SortObjects.h
enter code here- (NSString *)description {
return [NSString stringWithFormat:#"%# %#", self.firstName, self.lastName];
NSArray *firstNames = #[ #"Alice", #"Bob", #"Charlie", #"Quentin" ];
NSArray *lastNames = #[ #"Smith", #"Jones", #"Smith", #"Alberts" ];
NSArray *ages = #[ #24, #27, #33, #31 ];
NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
SortObjects *sObjects = [[SortObjects alloc] init];
sObjects.firstName = [firstNames objectAtIndex:idx];
sObjects.lastName = [lastNames objectAtIndex:idx];
sObjects.age = [ages objectAtIndex:idx];
[people addObject:sObjects];
}];
NSSortDescriptor *firstNameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"firstName"
ascending:YES
selector:#selector(localizedStandardCompare:)];
NSSortDescriptor *lastNameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"lastName"
ascending:YES
selector:#selector(localizedStandardCompare:)];
NSSortDescriptor *ageSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"age"
ascending:NO];
NSLog(#"By age: %#", [people sortedArrayUsingDescriptors:#[ageSortDescriptor]]);
value of sobj is coming null in nslog??

How to save and load a picture in Xcode

Check my app if you don't really understand ( Quick Notes!) But here it goes. My app is a notes app so it allows the user to select from few different kinds of note colors and designs below. When the user selects one, it changes the note above to what ever they set it to. So i need a button that will save the picture they selected, and when the leave the view and come back they can click the load button and the same image they selected will appear. I am using Xcode 4.3.
NSImageView is what your looking for.
This contains info on saving the file (look at the answer with code): Implement drag from NSImageView and save image to a file
The Code:
-(IBAction)saveImageButtonPushed:(id)sender
{
NSBitmapImageRep *rep;
NSData *data;
NSImage *image;
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
[self unlockFocus];
image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
[image addRepresentation:rep];
data = [rep representationUsingType: NSPNGFileType properties: nil];
//save as png but failed
[data writeToFile: #"asd.png" atomically: NO];
//save as pdf, succeeded but with flaw
data = [self dataWithPDFInsideRect:[self frame]];
[data writeToFile:#"asd.pdf" atomically:YES];
}
//......
#end
To load an image:
The Code:
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSDate *date = [[NSDate date] dateByAddingTimeInterval:1];
profile_img = [NSString stringWithFormat:#"%#.png",[dateFormatter stringFromDate:date]];
[profile_img retain];
NSLog(#"formattedDateString: %#",profile_img);
NSData *imageToUpload = UIImagePNGRepresentation(Img_View.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:ServerPath]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"Upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:profile_img mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject)
{
NSString *response = [operation2 responseString];
NSLog(#"response: [%#]",response);
NSString *post = [NSString stringWithFormat:#"Images=%#",profile_img];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [post length]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Gallery.php",ServerPath]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"POST"];
NSLog(#"%#", post);
[request1 setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody:postData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString *responseString = [[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding] autorelease];
responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",responseString);
if([responseString isEqualToString:#"Entered data successfully"])
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Image Share" message:#"Image Share SuccessFully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
else
{
}
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"error: %#", [operation2 error]);
}];
[operation2 start];

Can i use NSTimer in background?

I use
NSString *urlStr=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Delay is %#",result);
timer = [NSTimer scheduledTimerWithTimeInterval:(5)
target:self
selector:#selector(loginunlogin:)
userInfo:nil
repeats:YES];
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
}
-(void) loginunlogin:(NSTimer *)theTimer{
NSString *urlStr=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Delay is %#",result);
delay=[result floatValue];
if([result isEqual:#"false"]==TRUE){
NSLog(#"Delay %#",result);
}else{
NSLog(#"User logged delay is %#",result);
[timer invalidate];
timer=nil;
delay=[result floatValue];
NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval: delay target:self selector:#selector(targetMethod:)
userInfo:nil repeats:YES];
}
}
-(void) targetMethod: (NSTimer*)theTimer {
mapView =[[MKMapView alloc] init];
mapView.showsUserLocation=YES;
float mylo =mapView.userLocation.coordinate.longitude;
float myla =mapView.userLocation.coordinate.latitude;
NSString *str1 =[[NSString alloc] initWithFormat:#"%f",mylo];
NSString *str2 =[[NSString alloc] initWithFormat:#"%f",myla];
NSLog(#"longi %#",str1);
NSLog(#"latit %#",str2);
NSString *req=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/messages/getnewmessagescount?longitude=%#&latitude=%#",str1,str2];
NSURL *url = [NSURL URLWithString:req];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",request);
if ([result isEqual: #"0"])
{
NSLog(#"No messages");
}else{
if ([result isEqual:#"false"]) {
NSLog(#"Not logged");
}else{
NSString *path = [NSString stringWithFormat:#"%#%#",
[[NSBundle mainBundle] resourcePath],
#"/tada.wav"];
//declare a system sound id
SystemSoundID soundID;
//Get a URL for the sound file
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
//Use audio sevices to create the sound
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
//Use audio services to play the sound
AudioServicesPlaySystemSound(soundID);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *Date = [NSData date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:Date];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:Date];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [[NSString alloc] initWithFormat:#"Your have got (%#) new messages",result];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"someValue" forKey:#"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release]; NSLog(#"bla %#",result);
}}
}
How to change code that it works in background
I am using this code to play the sound when my application enter into background you can customize it for your own use
- (void)applicationDidEnterBackground:(UIApplication *)application{
backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[NSThread sleepForTimeInterval:3];
[self startPlayingInBackground:#"default.aif"];
NSLog(#"Time remaining: %f",[application backgroundTimeRemaining]);
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
// if you don't call endBackgroundTask, the OS will exit your app.
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
});
}
The line below is the code with help of which m playing the sound it's my objective c function all
[self startPlayingInBackground:#"default.aif"];

desktop wallpaper [duplicate]

I am trying to change the desktop image; the procedure I've come up with is below. The first time this code is run, the resized image is displayed on screen as wallpaper, but the next time there is no reaction. What am I doing wrong?
-(IBAction)click:(id)sender
{
NSData *sourceData;
NSError *error;
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
screenArray = [NSScreen screens];
screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
screenz = [screenArray objectAtIndex: index];
screenRect = [screenz visibleFrame];
}
NSLog(#"%fx%f",screenRect.size.width, screenRect.size.height);
arrCatDetails = [strCatDetails componentsSeparatedByString:appDelegate.strColDelimiter];
NSString *imageURL = [NSString stringWithFormat:#"upload/product/image/%#_%#_%d.jpg",[arrCatDetails objectAtIndex:0],appDelegate.str104by157Name,iSelectedImgIndex];
NSString *ima = [imageURL lastPathComponent];
NSString *str = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *dataFilePath = [str stringByAppendingPathComponent:ima];
NSString *imagePath = [NSString stringWithFormat:#"file://localhost%#",dataFilePath];
NSURL *url = [[NSURL alloc] init];
url = [NSURL URLWithString:imagePath];
sourceData = [NSData dataWithContentsOfURL:url];
sourceImage = [[NSImage alloc] initWithData: sourceData];
resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(screenRect.size.width, screenRect.size.height)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, screenRect.size.width, screenRect.size.height) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSBitmapImageRep* theImageRepresentation = [NSBitmapImageRep imageRepWithData:resizedData];
newimage = #"editwall.jpg";
newFilePath = [str stringByAppendingPathComponent:newimage];
NSData* theImageData = [theImageRepresentation representationUsingType:NSJPEGFileType properties:nil];
[theImageData writeToFile: newFilePath atomically: YES];
if([filemgr fileExistsAtPath:newFilePath] == YES)
{
imagePath1 = [NSString stringWithFormat:#"file://localhost%#",newFilePath];
urlz = [NSURL URLWithString:imagePath1];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:nil, NSWorkspaceDesktopImageFillColorKey, [NSNumber numberWithBool:NO], NSWorkspaceDesktopImageAllowClippingKey, [NSNumber numberWithInteger:NSImageScaleProportionallyUpOrDown], NSWorkspaceDesktopImageScalingKey, nil];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:urlz forScreen:[[NSScreen screens] lastObject] options:options error:&error];
}
else
{
NSLog(#"No");
}
[sourceImage release];
[resizedImage release];
}
Why not try -[NSWorkspace setDesktopImageURL:forScreen:options:error:]? Apple has a sample project called DesktopImage to give you some idea how to use it.
Edit (after reading your code more carefully):
The problem you're having may be because of your call to +[NSDictionary dictionaryWithObjectsAndKeys:] See the nil at the end of the list of arguments? That's how you tell NSDictionary that your argument list is done. You can't put nil in the list, because it will stop reading the list at that point. If you want to specify a key that has no value, you have to use [NSNull null].
An aside: you've got a memory management issue in your code:
// allocates memory for an NSURL
NSURL * url = [[NSURL alloc] init];
// allocates more memory for an NSURL, and leaks
// the earlier allocation
url = [NSURL URLWithString:imagePath];
Just do one or the other:
// If you do it this way, you will have to call
// [url release] later
NSURL * url = [[NSURL alloc] initWithString:imagePath];
// This memory will be released automatically
NSURL * otherUrl = [NSURL URLWithString:imagePath];

How to write Boolean to a plist file

I'm trying to write Boolean to a plist file. My code is:
NSString *filePath = [self dataFilePath];
if (filePath)
{
if (check)
{
NSLog(#"Clear");
[item setObject:[NSNumber numberWithBool:NO] forKey:#"check"];
[item writeToFile:filePath atomically: YES];
}else{
NSLog(#"Green");
[item setObject:[NSNumber numberWithBool:YES] forKey:#"check"];
[item writeToFile:filePath atomically: YES];
}
NSLog([[NSString alloc] initWithContentsOfFile:filePath]);
}else{
NSLog(#"write file was not found");
}
My filePath is:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"CheckMark.plist"];
}
I load my array with:
- (void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
NSLog(#"%#", filePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:#"CheckMark" ofType:#"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:filePath error:NULL];
}
// load our data from a plist file inside our app bundle
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog([[NSString alloc] initWithContentsOfFile:filePath]);
NSLog(#"%#", filePath);
NSLog(#"read dataArray");
Every thing works fine, except when I look at the plist file, nothing changes.
I'm writing the plist file to my Documents directory.
Thanks for any help you can give me.
Remember that you need to be using an NSMutableDictionary to be able to set values.

Resources