Converting nsarray to nsdata to nsstring to use in label - nsstring

Help from the more experienced Obj C coders will be greatly appreciated as I've been stuck on this for a few days, and I believe the code is 'close'.
I'm creating a list of names from the users contacts, then I pass this list back to a label. My problem (I think) is getting from the NSData format I'm using to archive the list with NSKeyedArchiver into an NSString. I've read everything I can find, but I suspect my being a NOOB is holding me back from deciphering some other example.
Here is the part of my *.m file where I create a list of persons into an array called "_objects", then I archive the "_objects" (NSKeyArchiver) making an NSData (data) which I then try to create a NSString (guestListString) from. It seems to all go well, except the "guestListString" has a bunch of extra gobblygook characters (yeah, a high tech term) included all around my list of person names. I've tried other formats, but they either return (null) or a bunch of foriegn looking characters. I suspect I've not learned some step I need to insert to get rid of these 'gobbly gook' characters around my list of comma separated names.
Here is the code:
// now grab the 'person' property from the Addressbook, pass it as a string back to 'tableview cell', inserting it at 'row 0' and update display
- (void)displayPerson:(ABRecordRef)person {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString *selectedPerson = (__bridge NSString *)ABRecordCopyCompositeName(person);
//NSString *firstname =(__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);
//NSString *lastname =(__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);
#ifdef DEBUG
NSLog(#"displayPerson insertRowsAtIndexPath selectedPerson = "#"%#",selectedPerson); // shows last added name
#endif
[_objects insertObject:selectedPerson atIndex:0];
//[_objects insertObject:firstname atIndex:0];
//[_objects insertObject:lastname atIndex:0];
#ifdef DEBUG
NSLog(#"displayPerson insertRowsAtIndexPath _objects = "#"%#",_objects); // shows 'list' of all names currently in list
//NSLog(#"displayPerson insertRowsAtIndexPath stringWithFormat _objects = "#"%#",[NSString stringWithFormat:#"%#",_objects]);
#endif
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//
// (Code to Archive an array) Given that "_objects" contains an array of 'selectedPerson' objects
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_objects];
// Now save to NSUser defaults
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"_objects"];
// Now let's see what is in 'data'
NSLog(#"archive of 'data' from key _objects = "#"%#",data); // shows long list of 8 bit numbers
//
// (Code to unarchive an array) Now to unarchive:
// I'm doing this code example here just so I understand unarchive procedure; not needed in actual app code
NSData *_objectsData = [[NSUserDefaults standardUserDefaults] objectForKey:#"_objects"];
NSArray *backIntoArray = [NSKeyedUnarchiver unarchiveObjectWithData:_objectsData];
//
// Now lets see what is in "backIntoArray"
NSLog(#"unarchive of _objectsData = "#"%#",_objectsData); // shows long list of 8 bit numbers
NSLog(#"unarchive of NSArray to backIntoArray = "#"%#",backIntoArray); // shows 'list' of all names currently in list
//
// Now convert NSData (data) to NSString so I can pass it to other elecments like 'labels'
//NSString *guestListString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is equivalent code to next two lines
NSString *guestListString;
guestListString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // returns extra characters around list of names instead of list of names ???
// other potential format options that could exist
//guestListString = [[NSString alloc] initWithData:data encoding:NSNEXTSTEPStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSJapaneseEUCStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSNEXTSTEPStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSSymbolStringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSShiftJISStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSISOLatin2StringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding]; // returns string of japanese looking characters???
//guestListString = [[NSString alloc] initWithData:data encoding:NSWindowsCP1251StringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSWindowsCP1252StringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSWindowsCP1253StringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSWindowsCP1254StringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSWindowsCP1250StringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSISO2022JPStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSMacOSRomanStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF16StringEncoding]; // returns string of japanese looking characters???
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF16BigEndianStringEncoding]; // shows
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF16LittleEndianStringEncoding]; // returns string of japanese looking characters???
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF32StringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF32BigEndianStringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSUTF32LittleEndianStringEncoding]; // returns (null) ???
//guestListString = [[NSString alloc] initWithData:data encoding:NSProprietaryStringEncoding]; // shows
//
// show me what is stored in NSString 'guestListString'
NSLog(#"displayPerson NSString conversion of 'data' to 'guestListString' = "#"%#",guestListString); //
//
// Pass the required text back to 'guestsListLabel.text' on ViewController screen
//((InitialViewController *)self.presentingViewController).guestListLabel.text=selectedPerson; // This WORKS passing back the last selectedPerson 1 name
((InitialViewController *)self.presentingViewController).guestListLabel.text=guestListString; // Not working yet; trying to pass back full list of names
//
// add code here to handle saving of guestlist before leavig this 'insertRowsAtIndexPath' section
// Archiving is simple, using the following code:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// This next line archives objects correctly so they can be reloaded later and be editable (mutable)
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_objects] forKey:#"guestListTable"];
// This next line writes the value loaded into 'guestListLabel.text' into variable 'kGuestListText' which is used in InitialViewController to display in all 3 field types
[userDefaults setValue:((InitialViewController *)self.presentingViewController).guestListLabel.text forKey:kGuestsListText];
// update with all userDefaults variables
[userDefaults synchronize];
//
}

Related

Buttons and textboxes not showing text

I'm trying to create a tile with 3 pages, each page contain a textbox and a button. Here is my code
[self.client.personalizationManager
themeWithCompletionHandler:^(MSBTheme *theme, NSError *error){
if (error){
// handle error
NSLog(#"Error: %#", error);
}
NSLog(#"Creating tile...");
NSString *tileName = #"SnapBand";
// Create Tile Icon
MSBIcon *tileIcon = [MSBIcon iconWithUIImage:[UIImage imageNamed:#"Band46x46.png"] error:nil];
// Create small Icon
MSBIcon *smallIcon = [MSBIcon iconWithUIImage:[UIImage imageNamed:#"Band24x24.png"] error:nil];
// Create a Tile
NSUUID *tileID = [[NSUUID alloc] initWithUUIDString:#"6120f0c7-fec4-44b0-99fa-04c7ca6cf869"];
MSBTile *tile = [MSBTile tileWithId:tileID name:tileName tileIcon:tileIcon smallIcon:smallIcon error:nil];
// Create a Picture Text Block
MSBPageTextBlock *pictureTextBlock = [self createMSBandTextBlockWithParameters:10 WithTheme:theme];
// Create a Picture Snap Button
MSBPageTextButton *pictureButton = [self createMSBandActioButtonWithParameters:11 WithTheme:theme];
// Create a Movie Text Block
MSBPageTextBlock *movieTextBlock = [self createMSBandTextBlockWithParameters:20 WithTheme:theme];
// Create a Movie Snap Button
MSBPageTextButton *movieButton = [self createMSBandActioButtonWithParameters:21 WithTheme:theme];
// Create a Brust Text Block
MSBPageTextBlock *brustTextBlock = [self createMSBandTextBlockWithParameters:30 WithTheme:theme];
// Create a Brust Snap Button
MSBPageTextButton *brustButton = [self createMSBandActioButtonWithParameters:31 WithTheme:theme];
MSBPageFlowPanel *pictureFlowPanel = [[MSBPageFlowPanel alloc] initWithRect:[MSBPageRect rectWithX:0 y:0 width:245 height:105]];
MSBPageFlowPanel *movieFlowPanel = [[MSBPageFlowPanel alloc] initWithRect:[MSBPageRect rectWithX:245 y:0 width:245 height:105]];
MSBPageFlowPanel *brustFlowPanel = [[MSBPageFlowPanel alloc] initWithRect:[MSBPageRect rectWithX:490 y:0 width:245 height:105]];
[pictureFlowPanel addElements:#[pictureTextBlock, pictureButton]];
[movieFlowPanel addElements:#[movieTextBlock, movieButton]];
[brustFlowPanel addElements:#[brustTextBlock, brustButton]];
MSBPageScrollFlowPanel *panel = [[MSBPageScrollFlowPanel alloc] initWithRect:[MSBPageRect rectWithX:0 y:0 width:245 height:105]];
panel.horizontalAlignment = MSBPageHorizontalAlignmentLeft;
panel.verticalAlignment = MSBPageVerticalAlignmentTop;
panel.orientation = MSBPageFlowPanelOrientationHorizontal;
[panel addElements:#[pictureFlowPanel, movieFlowPanel, brustButton]];
MSBPageLayout *layout = [[MSBPageLayout alloc] init];
layout.root = panel;
[tile.pageLayouts addObject:layout];
[self.client.tileManager addTile:tile completionHandler:^(NSError *error) {
if (!error || error.code == MSBErrorTypeTileAlreadyExist)
{
NSLog(#"Creating page...");
NSUUID *pageID = [[NSUUID alloc] initWithUUIDString:#"a234e9ba-1c09-46c3-b3b3-12bb1c9cf90f"];
NSArray *pageValues = #[[MSBPageTextButtonData pageTextButtonDataWithElementId:11 text:#"Snap!" error:nil],
[MSBPageTextBlockData pageTextBlockDataWithElementId:10 text:#"Picture" error:nil]];
MSBPageData *pageDataPicture = [MSBPageData pageDataWithId:pageID layoutIndex:0 value:pageValues];
NSUUID *pageIDMovie = [[NSUUID alloc] initWithUUIDString:#"1535d78b-9784-4892-a94c-030df63de453"];
NSArray *pageValuesMovie = #[[MSBPageTextButtonData pageTextButtonDataWithElementId:21 text:#"Snap!" error:nil],
[MSBPageTextBlockData pageTextBlockDataWithElementId:20 text:#"Movie" error:nil]];
MSBPageData *pageDataMovie = [MSBPageData pageDataWithId:pageIDMovie layoutIndex:1 value:pageValuesMovie];
NSUUID *pageIDBrust = [[NSUUID alloc] initWithUUIDString:#"1fd74789-3936-4324-a1fc-3e1d66d6e189"];
NSArray *pageValuesBrust = #[[MSBPageTextButtonData pageTextButtonDataWithElementId:31 text:#"Snap!" error:nil],
[MSBPageTextBlockData pageTextBlockDataWithElementId:30 text:#"Brust" error:nil]];
MSBPageData *pageDataBrust = [MSBPageData pageDataWithId:pageIDBrust layoutIndex:2 value:pageValuesBrust];
[self.client.tileManager setPages:#[pageDataPicture, pageDataMovie, pageDataBrust] tileId:tile.tileId completionHandler:^(NSError *error) {
if (!error)
{
NSLog(#"Completed band tile creation");
[self.snapPictureButton setBackgroundImage:[UIImage imageNamed:#"GreenStatus"] forState:UIControlStateNormal];
[self sendHapticFeedback];
}
else
{
NSLog(#"Error: %#", error.localizedDescription);
}
}];
}
else
{
NSLog(#"Error: %#", error.localizedDescription);
}
}];
}];
I created a constructor method to generate textboxes and buttons, the methods are:
-(MSBPageTextBlock *) createMSBandTextBlockWithParameters:(int)textBoxID WithTheme:(MSBTheme *) theme{
MSBPageTextBlock *textBlock = [[MSBPageTextBlock alloc] initWithRect:[MSBPageRect rectWithX:0 y:0 width:200 height:40] font:MSBPageTextBlockFontSmall];
textBlock.elementId = textBoxID;
textBlock.baselineAlignment = MSBPageTextBlockBaselineAlignmentRelative;
textBlock.horizontalAlignment = MSBPageHorizontalAlignmentLeft;
textBlock.autoWidth = YES;
textBlock.color = theme.baseColor;
textBlock.margins = [MSBPageMargins marginsWithLeft:15 top:0 right:0 bottom:0];
return textBlock;
}
and
-(MSBPageTextButton *) createMSBandActioButtonWithParameters:(int)textBoxID WithTheme:(MSBTheme *) theme{
MSBPageTextButton *actionButton = [[MSBPageTextButton alloc] initWithRect:[MSBPageRect rectWithX:0 y:0 width:200 height:40]];
actionButton.elementId = textBoxID;
actionButton.horizontalAlignment = MSBPageHorizontalAlignmentCenter;
actionButton.pressedColor = theme.baseColor;
actionButton.margins = [MSBPageMargins marginsWithLeft:15 top:0 right:0 bottom:0];
return actionButton;
}
The buttons and the textboxes doesn't show any text on the band, i can see the buttons on my band, the position of the third button is not correct, and there is no text in two of the buttons.
Can anyone help me?
Looks like you have created one layout with a horizontal scroll panel. And that panel has pictureFlowPanel, movieFlowPanel, brustButton as its elements.
So when you create pages you will just need to create one page with the above layout. However, in your code I see you are trying to create three pages with layout index 0, 1 and 2. Only layout 0 is valid and layouts 1 and 2 do not exist.
One possible fix is to break apart the layouts into three separate layouts:
MSBPageLayout *pictureLayout = [[MSBPageLayout alloc] init];
pictureLayout.root = pictureFlowPanel;
[tile.pageLayouts addObject:pictureLayout]; //Layout 0
MSBPageLayout *movieLayout = [[MSBPageLayout alloc] init];
movieLayout.root = movieFlowPanel;
[tile.pageLayouts addObject:movieLayout]; //Layout 1
MSBPageLayout *burstLayout = [[MSBPageLayout alloc] init];
burstLayout.root = burstFlowPanel;
[tile.pageLayouts addObject:burstLayout]; //Layout 2

Loading an audio sample from the documents folder

I'm trying to have an app play audio files added via itunes file-sharing. I've managed the app to retrieve the app's sandbox folder's content, but I'm not able to load such files into a C4Sample by specifying the complete path.
NSString *documentsFolder;
NSString *clickAudioPath;
C4Sample *clicksample;
-(void)setup {
// Retrieve the app's Documents folder
documentsFolder = [self applicationDocumentsDirectory];
clickAudioPath = [NSString stringWithFormat:#"%#/click.mp3", documentsFolder];
// Add test click audio
clicksample = [C4Sample sampleNamed:clickAudioPath];
[clicksample prepareToPlay];
[clicksample play];
}
// Get Documents folder
- (NSString *) applicationDocumentsDirectory{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
The above code doesn't play any sound, although I've doubled checked that clicksample actually refers to an existing file. How can I specify a complete path instead of just a name to load the audio?
Add a new method as below.
-(id) initWithURL:(NSURL *) soundFileURL
{
self = [super init];
if(self != nil) {
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
self.enableRate = YES;
self.player.delegate = self;
[self setup];
}
return self;
}

ios , get float level mic updateMesters when mic is recording audio

here is my code for recording now how can get the level sound input in mic by sample UIlable float number
i think i will use this function but how can i use this in rec.h & rec.m file
(void)updateMeters
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
recordedTmpName = [[NSString alloc] initWithFormat:#"%.0f.%#", [NSDate timeIntervalSinceReferenceDate] * 1000.0, #"aac"];
temporaryRecFile= [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:recordedTmpName]];
recorder = [[ AVAudioRecorder alloc] initWithURL:temporaryRecFile settings:recordSetting error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
During recording, you have to call updateMeters periodically, and get the average power by
- (float)averagePowerForChannel:(NSUInteger)channelNumber
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
- (void) handleTimer
{
[recorder updateMeters];
label.text = [NSString stringWithFormat:#"lf",[recorder averagePowerForChannel:0]];
}
To see more information, you can visit AVAudioRecorder Class Reference

plist - NSMutableDictionary - 0x0

I have a problem:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
NSString *settingPath = [[[NSString alloc] init] autorelease];
settingPath = [[NSBundle bundleWithPath:filePath] pathForResource:#"Root" ofType:#"plist"];
NSMutableDictionary *plist = [[[NSMutableDictionary alloc] init] autorelease];
plist = [NSMutableDictionary dictionaryWithContentsOfFile:settingPath];
after this plist is nil, adress ist 0x0 ... but why ?
Can anyone help me ?
Below is some code that should work OK:
NSString* path = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"plist"];
NSDictionary* dictionary = [NSDictionary dictionaryWithContentsOfFile:path];
Note that the plist must be valid, otherwise you will get a null value.
Also, note that you don't need to use alloc/init to create a variable if you're just going to overwrite its value in another call.

NSException error seems to occur randomly

This code was working fine, now for some reason I'm getting an NSException error that's generating a SIGABRT at the following line of code...
self.popoverController = [[[UIPopoverController alloc] initWithContentViewController:wbPopOverController] autorelease];
Here's the method it's located in...
-(IBAction)showPop:(id)sender {
//close any open popovers
[self.popoverController dismissPopoverAnimated:NO];
// Initialize wbPopUpViewController
PopoverAircraftClass *wbPopOverController = [[PopoverAircraftClass alloc] initWithNibName:#"PopoverAircraftClass" bundle:[NSBundle mainBundle]];
wbPopOverController.contentSizeForViewInPopover = CGSizeMake(175, 216);
wbPopOverController.delegate = self; //for update
[wbPopOverController setAircraftList:aircraftList withCurrentValue:activeRegistration];
// Object converted to UIPopOverController (retained so we can reference it)
self.popoverController = [[[UIPopoverController alloc] initWithContentViewController:wbPopOverController] autorelease];
self.popoverController.passthroughViews = [NSArray arrayWithObject: self.view];
[self.popoverController presentPopoverFromRect:[sender frame] inView:self.layoutViewIB permittedArrowDirections:UIPopoverArrowDirectionUp animated:NO];
[wbPopOverController release];
}
I'm new at this as you can probably tell. Any ideas as to what's generating the NSException?

Resources