Delegates in Objective-C - objective-c

I am trying to explore some codes in Objective-C. I came across an open source program - batch renamer. I was looking at its code and adding my own implementation. There is one thing in this code that I could not understand - I was hoping someone would be able to help me out.
The problem is that there is a renamer delegate "- (void)renamed" and I have no idea how it is called. So, I was wondering how does the program know when to call/use this delegate.
The code is as follows:
#import "ControllerMain.h"
static NSString *addFilesIdentifier = #"addFiles_item";
static NSString *removeFilesIdentifier = #"removeFiles_item";
static NSString *cleanAllIdentifier = #"cleanAll_item";
static NSString *updateUrl = #"http://www.hardboiled.it/software/update.xml";
#implementation ControllerMain
- (id)init
{
self = [super init];
//init some object
tableSource = [[NSMutableArray alloc] init];
updater = [[STUpdateChecker alloc] init];
renamer = [[STRenamer alloc] init];
//set some variables
withExt = NO;//for include the extension in the renaming, default NO
renamed = NO;//is YES after renaming preview
insoverappPosition = 0;
//set the notification for NSControlTextDidChangeNotification
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(textDidEndEditing:) name:#"NSControlTextDidChangeNotification" object:nil];
return self;
}
-(void)awakeFromNib
{
//set the delegates
[tabella setDelegate:self];
[tableSource setDelegate:self];
[renamer setDelegate:self];
[updater setDelegate:self];
//check if the software is updated
[updater checkUpdateWithUrl:[NSURL URLWithString:updateUrl]];
//drag' drop - set the dragged types
[tabella registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
//toolbar configuration
toolbar = [[NSToolbar alloc] initWithIdentifier:#"toolbar"];
[toolbar setDelegate:self];
//mainWindows properties
[mainWindow center];
[mainWindow setTitle:#"macXrenamer"];
[mainWindow setToolbar:toolbar];
//set the extension checkbox
[extSwitch setState:0];
//Set the custom cell imageAndTextCell
ImageAndTextCell *imageAndTextCell = nil;
NSTableColumn *tableColumn = nil;
tableColumn = [tabella tableColumnWithIdentifier:#"original_name"];
imageAndTextCell = [[[ImageAndTextCell alloc] init] autorelease];
[imageAndTextCell setEditable: NO];
[tableColumn setDataCell:imageAndTextCell];
//
//initialize the window for empty table
[self tableSourceIsEmpty];
//release the toolbar
[toolbar release];
}
- (void)dealloc
{
//release all
[tabella unregisterDraggedTypes];
[tableSource release];
[renamer release];
[super dealloc];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
//close the application
return YES;
}
/* ################### tableSource delegates #################################*/
- (void)tableSourceIsEmpty
{
if (KDEBUG)
NSLog(#"tablesource is empty");
[upper_lower setEnabled:NO];
[from setEditable:NO];
[to setEditable:NO];
[insertText setEditable:NO];
[insertAtPosition setEditable:NO];
[insertAtPosition setIntValue:0];
[renameButton setEnabled:NO];
[annullButton setEnabled:NO];
[searchField setEditable:NO];
[replaceField setEditable:NO];
}
- (void)tableSourceIsNotEmpty
{
if (KDEBUG)
NSLog(#"tablesource is not empty");
[upper_lower setEnabled:YES];
[from setEditable:YES];
[to setEditable:YES];
[insertText setEditable:YES];
[insertAtPosition setEditable:YES];
[searchField setEditable:YES];
[replaceField setEditable:YES];
}
-(void)tableSourceDidChange
{
NSString *countString = [NSString stringWithFormat:#"%d files",[tableSource count]];
[number_of_files setStringValue:countString];
}
/*####################end tableSource delegates###############################*/
/*######################renamer delegates#####################################*/
- (void)renamed
{
NSLog(#"renaming preview ok");
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
[insertAtPosition setTextColor:[NSColor blackColor]];
}else if([tabViewId isEqual:#"remove"])
{
[from setTextColor:[NSColor blackColor]];
[to setTextColor:[NSColor blackColor]];
}
renamed = YES;
[renameButton setEnabled:YES];
[annullButton setEnabled:YES];
}
- (void)notRenamed
{
renamed = NO;
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
[insertAtPosition setTextColor:[NSColor redColor]];
}else if([tabViewId isEqual:#"remove"])
{
[from setTextColor:[NSColor redColor]];
[to setTextColor:[NSColor redColor]];
}
NSLog(#"exception in preview delegate");
[renameButton setEnabled:NO];
}
/* ###################end renamer delegates ##################################*/
//make the file extension editable
-(IBAction)makeExtEditable:(id)sender
{
if (KDEBUG)
NSLog(#"makeExtEditable action");
if ([sender state] == 0) {
withExt = NO;
}else if ([sender state] == 1) {
withExt = YES;
}
}
//add files to the table
-(IBAction)addFiles:(id)sender
{
//start the progression bar
[progBar startAnimation:self];
int result;
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setCanChooseFiles:YES];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setResolvesAliases:NO];
result = [oPanel runModalForTypes:nil];
if (result == NSOKButton) {
NSArray *filesToOpen = [oPanel filenames];
[tableSource add:filesToOpen];
[tabella reloadData];
}
//stop the progression bar
[progBar stopAnimation:self];
}
//remove files from the table
-(IBAction)removeFiles:(id)sender
{
if(KDEBUG)
NSLog(#"remove the selected file from the table");
[progBar startAnimation:self];
NSIndexSet *selected = [tabella selectedRowIndexes];
[tableSource removeAtIndexes:selected];
[tabella reloadData];
[progBar stopAnimation:self];
}
//remove all files from the table
-(IBAction)clearTable:(id)sender
{
if(KDEBUG)
NSLog(#"clear all table");
[progBar startAnimation:self];
[tableSource cleanAll];
[tabella reloadData];
[progBar stopAnimation:self];
}
//annull
-(IBAction)annulRenaming:(id)sender
{
[tableSource annull];
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
[insertAtPosition setTextColor:[NSColor blackColor]];
}else if([tabViewId isEqual:#"remove"])
{
[from setTextColor:[NSColor blackColor]];
[to setTextColor:[NSColor blackColor]];
}
renamed = NO;
[renameButton setEnabled:NO];
[tabella reloadData];
}
/*###########################log section######################################*/
-(IBAction)showLogWindows:(id)sender{
if ([logWindow isVisible]) {
[logWindow setIsVisible:FALSE];
}else {
[logWindow setIsVisible:TRUE];
}
}
-(void)addToLog:(NSString *)text
{
NSString *textLog = [text stringByAppendingString:#"\n\r"];
NSRange endRange;
endRange.location = [[logField textStorage] length];
endRange.length = 0;
[logField replaceCharactersInRange:endRange withString:textLog];
endRange.length = [textLog length];
[logField scrollRangeToVisible:endRange];
}
/*#######################end log section######################################*/
/*######################editing actions#######################################*/
-(IBAction)finalRenaming:(id)sender
{
if(KDEBUG)
NSLog(#"renaming button pressed");
//start the progression bar
[progBar startAnimation:self];
//count of the files really renamed
int countRenamed = 0;
//count of the renaming error
int errRenamed = 0;
//the result of rename()
int renameResult;
//the enumerator and the obj
NSEnumerator *en = [tableSource objectEnumerator];
id row;
if(renamed)
{
while(row = [en nextObject])
{
renameResult = rename([[row objectAtIndex:0] fileSystemRepresentation], [[row objectAtIndex:1] fileSystemRepresentation]);
if(renameResult == 0){
NSString *textLog = [NSString stringWithFormat:#"%# renamed with\n %#", [row objectAtIndex:0],[row objectAtIndex:1]];
NSLog(textLog);
[self addToLog:textLog];
countRenamed++;
}else {
NSString *textLog =[NSString stringWithFormat: #"Error in file renaming %#", [row objectAtIndex:0]];
NSLog(textLog);
[self addToLog:textLog];
errRenamed++;
}
}
if(errRenamed >0){
//open the panel alert
int result;
result = NSRunAlertPanel(#"Renaming error. Please check the log", #"Error!", #"Ok", NULL, NULL);
}
//print the result of renaming
[notiField setStringValue:[NSString stringWithFormat:#"renamed %d/%d files, %d errors", countRenamed,[tableSource count],errRenamed]];
//
[tableSource reinitialize];
[tabella reloadData];
[renameButton setEnabled:NO];
[annullButton setEnabled:NO];
[progBar stopAnimation:self];
}
}
- (void)textDidEndEditing:(NSNotification *)aNotification
{
[progBar startAnimation:self];
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
if(KDEBUG)
NSLog(#"insert selected");
if(insoverappPosition == 1)
{
if(KDEBUG)
NSLog(#"overwrite selected");
tableSource = [renamer overwriteChar:tableSource insertText:[insertText stringValue] position:[insertAtPosition intValue] withExt:withExt];
}else if(insoverappPosition == 0){
if(KDEBUG)
NSLog(#"insert selected");
tableSource = [renamer insertChar:tableSource insertText:[insertText stringValue] position:[insertAtPosition intValue] withExt:withExt];
}else if(insoverappPosition == 2){
if(KDEBUG)
NSLog(#"append selected");
tableSource = [renamer appendChar:tableSource appendText:[insertText stringValue] withExt:withExt];
}
}else if ([tabViewId isEqual:#"remove"]) {
if(KDEBUG)
NSLog(#"remove selected");
tableSource = [renamer removeChar:tableSource from:[from intValue] to:[to intValue] withExt:withExt];
}else if([tabViewId isEqual:#"search"]){
if(KDEBUG)
NSLog(#"search selected");
tableSource = [renamer searchAndReplace:tableSource string:[searchField stringValue] withString:[replaceField stringValue] withExt:withExt];
}
[progBar stopAnimation:self];
}
-(IBAction)upLowerCellClicked:(id)sender
{
NSCell* cell;
cell = [upper_lower selectedCell];
int tag = [cell tag];
if (tag == 0) {
if(KDEBUG)
NSLog(#"lowercase selected");
tableSource = [renamer makeLowerCase:tableSource withExt:withExt];
[renameButton setEnabled:YES];
[annullButton setEnabled:YES];
[tabella reloadData];
}
else if(tag == 1){
if(KDEBUG)
NSLog(#"uppercase selected");
tableSource = [renamer makeUpperCase:tableSource withExt:withExt];
[renameButton setEnabled:YES];
[annullButton setEnabled:YES];
[tabella reloadData];
}
}
-(IBAction)insertOverwriteClicked:(id)sender
{
if(KDEBUG)
NSLog(#"insertOverwriteClicked");
NSCell* cell;
cell = [insert_overwrite selectedCell];
int tag = [cell tag];
if(tag == 0)
{
if(KDEBUG)
NSLog(#"insert");
[insertAtPosition setEnabled:YES];
insoverappPosition = 0;
}else if(tag==1){
if(KDEBUG)
NSLog(#"overwrite");
[insertAtPosition setEnabled:YES];
insoverappPosition = 1;
}else if (tag==2) {
if(KDEBUG)
NSLog(#"append");
[insertAtPosition setEnabled:NO];
insoverappPosition = 2;
}
}
/*################end editing actions#########################################*/
-(void)newUpdateIsOnline
{
NSLog(#"newUpdateIsOnline");
BOOL retval;
retval = (NSAlertDefaultReturn == NSRunAlertPanel(#"Update Available", #"Update now or later", #"Update", #"Cancel", nil, nil));
if(retval){
if(KDEBUG)
NSLog(#"update now");
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:#"http://www.hardboiled.it/software/rinominatore-upgrade.zip"]];
//to edit
//[[NSNotificationCenter defaultCenter] postNotificationName:#"openSheetNotification" object:self userInfo:nil];
}else {
if(KDEBUG)
NSLog(#"cancel the update");
}
//release the updater. now is useless
[updater release];
}
/*################nstableview delegates#######################################*/
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
return [tableSource count];
}
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
if ([[aTableColumn identifier] isEqualToString: #"original_name"]) {
id obj = [tableSource objectAtRow:rowIndex atIndex:0] ;
return [obj lastPathComponent];
//return theIcon;
}else if([[aTableColumn identifier] isEqualToString: #"new_name"]){
id obj = [tableSource objectAtRow:rowIndex atIndex:1] ;
return [obj lastPathComponent];
}
return nil;
}
- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
if(cell_with_icon)
{
if ( [[aTableColumn identifier] isEqualToString:#"original_name"] ){
[((ImageAndTextCell*) cell) setImage:[tableSource objectAtRow:rowIndex atIndex:2]];
}
}
}
/* ###############end nstableview delegates #################################*/
/*############### nstoolbar delegates #######################################*/
- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
{
return [NSArray arrayWithObjects:addFilesIdentifier,
removeFilesIdentifier,cleanAllIdentifier,
NSToolbarFlexibleSpaceItemIdentifier,
NSToolbarSpaceItemIdentifier,
NSToolbarSeparatorItemIdentifier, nil];;
}
- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *)toolbar
{
return [NSArray arrayWithObjects:addFilesIdentifier,
removeFilesIdentifier,NSToolbarFlexibleSpaceItemIdentifier,cleanAllIdentifier, nil];
}
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
NSToolbarItem *toolbarItem = nil;
if ([itemIdentifier isEqualTo:addFilesIdentifier]) {//button addfiles
toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[toolbarItem setLabel:#"Add"];
[toolbarItem setPaletteLabel:[toolbarItem label]];
[toolbarItem setToolTip:#"Add"];
[toolbarItem setImage:[NSImage imageNamed:#"add.icns"]];
[toolbarItem setTarget:self];
[toolbarItem setAction:#selector(addFiles:)];
}else if ([itemIdentifier isEqualTo:removeFilesIdentifier]) {//button remove files
toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[toolbarItem setLabel:#"Remove"];
[toolbarItem setPaletteLabel:[toolbarItem label]];
[toolbarItem setToolTip:#"Remove"];
[toolbarItem setImage:[NSImage imageNamed:#"remove.icns"]];
[toolbarItem setTarget:self];
[toolbarItem setAction:#selector(removeFiles:)];
}else if ([itemIdentifier isEqualTo:cleanAllIdentifier]) {//button clean
toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[toolbarItem setLabel:#"Clean All"];
[toolbarItem setPaletteLabel:[toolbarItem label]];
[toolbarItem setToolTip:#"Clean the table"];
[toolbarItem setImage:[NSImage imageNamed:#"cleanAll.icns"]];
[toolbarItem setTarget:self];
[toolbarItem setAction:#selector(clearTable:)];
}
return [toolbarItem autorelease];
}
/*###############end nstoolbar delegates #####################################*/
/*################drag'n drop delegates #####################################*/
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
// Drag and drop support
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
[pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:self];
[pboard setData:data forType:NSFilenamesPboardType];
return YES;
}
- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op
{
// Add code here to validate the drop
if (KDEBUG)
NSLog(#"validate Drop");
return NSDragOperationEvery;
}
- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id )info row:(int)row dropOperation:(NSTableViewDropOperation)op
{
if (KDEBUG)
NSLog(#"acceptDrop");
NSPasteboard *pboard = [info draggingPasteboard];
if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
[tableSource add:files];
}
[tabella reloadData];
return YES;
}
/*################end drag'n drop delegates ##################################*/
#end

The delegate is the object, not the method. The ControllerMain object is set as some other object's delegate. When that other object sees the condition that tells it renaming has occurred (whatever that means), it executes something along the lines of [[self delegate] renamed], which calls the ControllerMain method.

Related

Unable to call up my video files using AVFoundation

I'm having difficulty playing back video that I've recently recorded in a hybrid image/video camera akin to Snapchat (e.g. tap to take a photo, press and hold to record a video, playback on button release).
I'm currently saving the video file to NSFileManager. When I log it out I do verify that something is being saved but can't inspect the file because it has to be tested on the phone.
The file path when I log it out:
file:///var/mobile/Containers/Data/Application/7D86B14D-ACFF-4494-AD61-CBBD32DCA7A5/Documents/test.mov
When I go to load the asset from the file manager I log out an error that it can't open the files. I've only just started working with AVFoundation so not sure what some of the issues/considerations are when debugging. Any insight would be greatly appreciated, thank you!
Referenced tutorial
Referenced github repository
Referenced code:
PlayerView.h (reference)
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface PlayerView : UIView
#property (nonatomic) AVPlayer *player;
- (void)setPlayer:(AVPlayer *)player;
#end
PlayerView.m (reference)
#import "PlayerView.h"
#implementation PlayerView
+ (Class)layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer *)player {
return [(AVPlayerLayer *)[self layer] player];
}
- (void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
#end
HybridCameraViewController.h (reference)
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import "PlayerView.h"
#interface HybridCameraViewController : UIViewController
#property UIButton *button;
#property UIButton *saveButton;
#property UIImageView *previewView;
#define VIDEO_FILE #"test.mov"
#end
HybridCameraViewController.m (reference)
#import "HybridCameraViewController.h"
static const NSString *ItemStatusContext;
#class PlayerView;
#interface HybridCameraViewController () <AVCaptureFileOutputRecordingDelegate>
#end
#implementation HybridCameraViewController
AVCaptureSession *session;
AVCaptureStillImageOutput *imageOutput;
AVCaptureMovieFileOutput *movieOutput;
AVCaptureConnection *videoConnection;
AVPlayer *player;
AVPlayerItem *playerItem;
PlayerView *playerView;
- (void)viewDidLoad {
[super viewDidLoad];
[self testDevices];
self.view.backgroundColor = [UIColor blackColor];
//Image preview
self.previewView = [[UIImageView alloc]initWithFrame:self.view.frame];
self.previewView.backgroundColor = [UIColor whiteColor];
self.previewView.contentMode = UIViewContentModeScaleAspectFill;
self.previewView.hidden = YES;
[self.view addSubview:self.previewView];
//Playerback setup
playerView = [[PlayerView alloc]initWithFrame:self.view.frame];
playerView.backgroundColor = [UIColor redColor];
[self syncUI];
//Buttons
self.button = [self createButtonWithTitle:#"REC" chooseColor:[UIColor redColor]];
UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:#selector(handleLongPressGesture:)];
[self.button addGestureRecognizer:longPressRecognizer];
[self.button addTarget:self action:#selector(captureImage) forControlEvents:UIControlEventTouchUpInside];
self.saveButton = [self createSaveButton];
[self.saveButton addTarget:self action:#selector(saveActions) forControlEvents:UIControlEventTouchUpInside];
}
- (void)viewWillAppear:(BOOL)animated {
//Tests
[self initializeAVItems];
NSLog(#"%#", videoConnection);
NSLog(#"%#", imageOutput.connections);
NSLog(#"%#", imageOutput.description.debugDescription);
}
#pragma mark - AV initialization
- (void)initializeAVItems {
//Start session, input
session = [AVCaptureSession new];
if ([session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
session.sessionPreset = AVCaptureSessionPresetHigh;
}
AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
if ([session canAddInput:deviceInput]) {
[session addInput:deviceInput];
} else {
NSLog(#"%#", error);
}
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
//Layer preview
CALayer *viewLayer = [[self view] layer];
[viewLayer setMasksToBounds:YES];
CGRect frame = self.view.frame;
[previewLayer setFrame:frame];
[viewLayer insertSublayer:previewLayer atIndex:0];
//Image Output
imageOutput = [AVCaptureStillImageOutput new];
NSDictionary *imageOutputSettings = [[NSDictionary alloc]initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
imageOutput.outputSettings = imageOutputSettings;
//Video Output
movieOutput = [AVCaptureMovieFileOutput new];
[session addOutput:movieOutput];
[session addOutput:imageOutput];
[session startRunning];
}
- (void)testDevices {
NSArray *devices = [AVCaptureDevice devices];
for (AVCaptureDevice *device in devices) {
NSLog(#"Device name: %#", [device localizedName]);
if ([device hasMediaType:AVMediaTypeVideo]) {
if ([device position] == AVCaptureDevicePositionBack) {
NSLog(#"Device position : back");
}
else {
NSLog(#"Device position : front");
}
}
}
}
#pragma mark - Image capture
- (void)captureImage {
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in imageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
videoConnection = connection;
break;
}
}
if (videoConnection) {
break;
}
}
NSLog(#"Requesting capture from: %#", imageOutput);
[imageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [UIImage imageWithData:imageData];
self.previewView.image = image;
self.previewView.hidden = NO;
}
}];
[self saveButtonFlyIn:self.saveButton];
}
#pragma mark - Video capture
- (void)captureVideo {
NSLog(#"%#", movieOutput.connections);
[[NSFileManager defaultManager] removeItemAtURL:[self outputURL] error:nil];
videoConnection = [self connectionWithMediaType:AVMediaTypeVideo fromConnections:movieOutput.connections];
[movieOutput startRecordingToOutputFileURL:[self outputURL] recordingDelegate:self];
}
- (AVCaptureConnection *)connectionWithMediaType:(NSString *)mediaType fromConnections:(NSArray *)connections {
for (AVCaptureConnection *connection in connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:mediaType]) {
return connection;
}
}
}
return nil;
}
#pragma mark - Show Last Recording
- (void)presentRecording {
NSLog(#"unplaying");
NSLog(#"%#",[self outputURL]);
}
- (IBAction)loadAssetFromFile {
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[self outputURL] options:nil];
NSString *tracksKey = #"tracks";
[asset loadValuesAsynchronouslyForKeys:#[tracksKey] completionHandler:^{
dispatch_async(dispatch_get_main_queue(),^{
NSError *error;
AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey
error:&error];
if (status == AVKeyValueStatusLoaded) {
playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem addObserver:self forKeyPath:#"status"
options:NSKeyValueObservingOptionInitial
context:&ItemStatusContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:playerItem];
player = [AVPlayer playerWithPlayerItem:playerItem];
[playerView setPlayer:player];
}
else {
NSLog(#"The asset's tracks were not loaded:\n%#", [error localizedDescription]);
}
});
}];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == &ItemStatusContext) {
dispatch_async(dispatch_get_main_queue(),^{
[self syncUI];
});
return;
}
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
return;
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
[player seekToTime:kCMTimeZero];
}
- (void)syncUI {
if ((player.currentItem != nil) &&
([player.currentItem status] == AVPlayerItemStatusReadyToPlay)) {
self.button.enabled = YES;
}
else {
self.button.enabled = NO;
}
}
#pragma mark - AVCaptureFileOutputRecordingDelegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
if (!error) {
NSLog(#"Success!!!!");
} else {
NSLog(#"Error: %#", [error localizedDescription]);
}
}
#pragma mark - Recoding Destination URL
- (NSURL *)outputURL {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:VIDEO_FILE];
return [NSURL fileURLWithPath:filePath];
}
#pragma mark - Buttons
- (void)handleLongPressGesture:(UILongPressGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateBegan) {
NSLog(#"Press");
self.button.backgroundColor = [UIColor greenColor];
[self captureVideo];
}
if (recognizer.state == UIGestureRecognizerStateEnded) {
NSLog(#"Unpress");
self.button.backgroundColor = [UIColor redColor];
[movieOutput stopRecording];
[self performSelector:#selector(loadAssetFromFile)];
[player play];
}
}
- (UIButton *)createButtonWithTitle:(NSString *)title chooseColor:(UIColor *)color {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.frame.size.height - 100, 85, 85)];
button.layer.cornerRadius = button.bounds.size.width / 2;
button.backgroundColor = color;
button.tintColor = [UIColor whiteColor];
[self.view addSubview:button];
return button;
}
- (UIButton *)createSaveButton {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width, self.view.frame.size.height - 100, 85, 85)];
button.layer.cornerRadius = button.bounds.size.width / 2;
button.backgroundColor = [UIColor greenColor];
button.tintColor = [UIColor whiteColor];
button.userInteractionEnabled = YES;
[button setTitle:#"save" forState:UIControlStateNormal];
[self.view addSubview:button];
return button;
}
- (void)saveButtonFlyIn:(UIButton *)button {
CGRect movement = button.frame;
movement.origin.x = self.view.frame.size.width - 100;
[UIView animateWithDuration:0.2 animations:^{
button.frame = movement;
}];
}
- (void)saveButtonFlyOut:(UIButton *)button {
CGRect movement = button.frame;
movement.origin.x = self.view.frame.size.width;
[UIView animateWithDuration:0.2 animations:^{
button.frame = movement;
}];
}
#pragma mark - Save actions
- (void)saveActions {
[self saveButtonFlyOut:self.saveButton];
self.previewView.image = nil;
self.previewView.hidden = YES;
}
#end
The approach was overly complex. Where you went wrong was 1) not loading the url properly and 2) not adding the 'player layer' sublayer to the main view.
Here is an example of successful playback:
//TestURL
self.videoURL = [NSURL URLWithString:(NSString *)[self.selectedVideo objectForKey:#"source"]];
//Video
self.player = [AVPlayer playerWithPlayerItem:[[AVPlayerItem alloc]initWithAsset:[AVAsset assetWithURL:self.videoURL]]];
//Player layer
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
self.playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3);
[self.view.layer addSublayer:self.playerLayer];
[self.player play];
All you would need to do is redirect the url to the one you just saved:
self.videoURL = [self outputURL];

Iphone uitextfield auto format like contacts app tag issue

I have a form screen on my iphone and I am trying to replicate the Iphone Contacts app where it will auto complete the following format for the phone number:
(233)323-2323.
I am very close I am able to see the format update in the textfield but the 4 other text fields are not working now. I am unable to edit them. I narrowed it down to the shouldchangecharactersinrange function.
Please see code below.
Thanks.
quick look at the method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
Firstcontroller.h
#interface FirstTVContoller : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate>{
NSMutableArray *items;
NSMutableArray *titles;
NSMutableArray *section2items;
NSMutableArray *dataArray;
UITableView *table;
contactTitle *title;
//launch title picker
UIPickerView *titlePicker;
UILabel *titleLabel;
UITextField *titleField;
UIActionSheet *actionSheet;
UIPickerView *pickerView;
UITextField *textField;
UITextField *FirstnameTextfield;
UITextField *LastnameTextfield;
UITextField *CompanyTextfield;
UITextField *phoneTextfield;
//the scrollview
UIScrollView *scrollview;
}
//attributes for title picker
#property (strong, nonatomic) NSArray * titlecategories;
#property (strong, nonatomic) NSArray * titleidSlot;
#end
FirstTVController.m
//
// FirstTVContoller.m
// TwoTableViews
#implementation FirstTVContoller
#synthesize titleidSlot;
#synthesize titlecategories;
- (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
//NSLog(#"Error. Could not recover network reachability flags");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:SERVERNAME];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}
-(void)viewDidLoad{
[super viewDidLoad];
// scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
// scrollview.pagingEnabled = YES;
//
// //[scrollview addSubview:self.view];
// [self.view addSubview:scrollview];
table.scrollEnabled = YES;
dataArray = [[NSMutableArray alloc] init];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 30)];
//dropper
titleField = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 300, 30)];
titleField.layer.cornerRadius = 8;
titleField.backgroundColor = [UIColor clearColor];
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:#"data"];
[dataArray addObject:firstItemsArrayDict];
//Second section dat
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:#"1", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:#"data"];
[dataArray addObject:secondItemsArrayDict];
NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:#"data"];
[dataArray addObject:thirdItemsArrayDict];
NSLog(#"the dataArray%#",dataArray);
if([self connectedToNetwork]){
dispatch_async(kBgQueue, ^{
//build the url of strings
FULLURL = [SERVERNAME stringByAppendingFormat:ushTitleLink];
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
//NSLog(#"here title url%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
NSLog(#"here%#",data);
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
NSLog(#"titleid:%#",TITLEID);
NSLog(#"title categories:%#",titlecategories);
});
[table setBounces:NO];
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Please Check your internet connection"
message:#"Enable your internet connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
});
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [dataArray count];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [dataArray objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"data"];
return [array count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 1){
cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"longdropper300.png"]];
}
else{
cell.backgroundColor = [UIColor whiteColor];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10, 290, 30)];
static NSString *cellValue = #"Cell";
UITableViewCell *cell =nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellValue];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if ([indexPath section] == 0) {
//cellValue=[items objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle= UITableViewCellSelectionStyleNone;
//textField.tag = 1;
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor blackColor];
if(indexPath.section == 0){
//textfield for email
if ([indexPath row] == 0) {
textField.tag = 1;
textField.text = EMAIL;
textField.textColor= [UIColor blackColor];
textField.placeholder = #"Email: example#gmail.com";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
//textfield for phone number
else {
textField.tag = 2;
if ([PHONENUMBER isEqual: [NSNull null]] && PHONENUMBER == nil && PHONENUMBER == NULL && [PHONENUMBER isEqual: #""]){
NSLog(#"phone is empty%#",PHONENUMBER);
//[PHONENUMBER isEqual:#"frank"];
}else{
NSLog(#"phone is not empty%#",PHONENUMBER);
textField.text = PHONENUMBER;
}
textField.placeholder = #"Phone: (xxx)xxx-xxxx";
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDefault;
textField.secureTextEntry = NO;
}
textField.backgroundColor = [UIColor whiteColor];
//textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
//textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
//textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
}
if(indexPath.section == 1){
[titleField setTextColor:[UIColor whiteColor]];
titleField.tag = 3;
titleField.placeholder = #"Select Contact Title";
titleField.returnKeyType = UIReturnKeyNext;
//titleField == textField.tag = 3;
if ([TITLENAME isEqual: [NSNull null]]){
NSLog(#"titlename is empty%#",TITLENAME);
}else{
NSLog(#"titlename is not empty%#",TITLENAME);
titleField.text = TITLENAME;
}
titleField.keyboardType = UIKeyboardTypeDefault;
titleField.returnKeyType = UIReturnKeyDone;
titleField.secureTextEntry = NO;
titleField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
titleField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
titleField.textAlignment = UITextAlignmentCenter;
titleField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[titleField setEnabled: NO];
titleField.delegate = self;
[cell addSubview:titleField];
NSLog(#"here is the titlename%#",TITLENAME);
}
if(indexPath.section == 2){
if ([indexPath row] == 0) {
textField.tag = 4;
textField.placeholder = #"First Name";
cell.selectionStyle= UITableViewCellSelectionStyleNone;
if ([FIRSTNAME isEqual: [NSNull null]]){
NSLog(#"firstname is empty%#",FIRSTNAME);
textField.text = #"";
}else{
textField.text = FIRSTNAME;
}
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
if([indexPath row] == 1){
textField.tag = 5;
textField.placeholder = #"Last Name";
if ([LASTNAME isEqual: [NSNull null]]){
NSLog(#"lastname is empty%#",LASTNAME);
textField.text = #"";
}else{
textField.text = LASTNAME;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyNext;
//textField.secureTextEntry = NO;
}
if([indexPath row] == 2){
textField.tag = 6;
textField.placeholder = #"Company";
if ([COMPANY isEqual: [NSNull null]]){
NSLog(#"company is empty%#",COMPANY);
textField.text = #"";
}
else{
textField.text = COMPANY;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
//]textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
return cell;
}
//Change the Height of title cell drop down
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if (indexPath.section == 1) {
if (indexPath.row == 0) {
return 30;
}
}
return 45;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if(([textField tag] == 1)){
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:textField.text] == YES)
{
EMAIL = [textField.text copy];
NSLog(#"here is the email%#",EMAIL);
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Bad Email"
message: #"Please Re-enter the email address with a valid email"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
NSLog(#"email not in proper format");
}
}
if(([textField tag] == 2)){
//NSString *phoneRegex = #"[235689][0-9]{6}([0-9]{3})?";
//NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
//valid email address
//if ([phoneTest evaluateWithObject:textField.text] == YES)
// {
//if(PHONENUMBER != nil){
NSString *tempString = [textField.text copy];
NSString *unformatted = tempString;
NSLog(#"unformatted phonenumber%#",unformatted);
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
[unformatted substringWithRange:NSMakeRange(3, 3)],
[unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"(%#)%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
NSLog(#"Formatted Phone Number: %#", formattedString);
PHONENUMBER = formattedString;
NSLog(#"here is the phone number %#",PHONENUMBER);
// }
// else
// {
// NSLog(#"Phone Number Invalid");
// UIAlertView *alert = [[UIAlertView alloc]
// initWithTitle: #"xxx-xxx-xxxx"
// message: #"Please enter a valid phone number"
// delegate: nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
// textField.text = nil;
// }
}
if(([textField tag] == 4)){
FIRSTNAME = [textField.text copy];
NSLog(#"here is the firstName%#",FIRSTNAME);
}
if(([textField tag] == 5)){
LASTNAME = [textField.text copy];
NSLog(#"here is the Last Name%#",LASTNAME);
}
if(([textField tag] == 6)){
COMPANY = [textField.text copy];
NSLog(#"here is the Company%#",COMPANY);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
title = [[contactTitle alloc] initWithDictionary:json];
//NSLog(#"here is the dictionary from json: %#", json);
NSLog(#"here is title that was the json %#", title);
NSLog(#"here is the title from json: %#", title.cTitle);
NSLog(#"here is the title id from json %#", title.cTitleID);
}
//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
dispatch_queue_t downloadQueue = dispatch_queue_create("data loader", NULL);
dispatch_async(downloadQueue, ^{
TITLENAME = [title.cTitle objectAtIndex:row], row;
//NSLog(#"here is the selected title%#", TITLENAME);
TITLEID = [title.cTitleID objectAtIndex:row], row;
//NSLog(#"here is the selected title%#", TITLEID);
});
//thePickerView.hidden = YES;
}
//PickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [title.cTitle count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [title.cTitle
objectAtIndex:row];
}
- (void)fetchedContactIDData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(#"here is the login info from json: %#", json);
// NSString *FALSELOGIN;
CONTACTID = [json valueForKey:#"contactid"];
NSLog(#"CONTACT ID: %#", CONTACTID);
// LOGINID = [json valueForKey:#"login"];
// NSLog(#"LOGIN ID: %#", LOGINID);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get the country selected
//NSString *selectedCell = nil;
if(indexPath.section == 1){
titleField.text = #"Select Contact Title";
NSLog(#"you selected:%#",TITLENAME);
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:#"Cancel"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:#selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
//[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet showInView:self.view];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}else{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
- (void)dismissActionSheet:(id)sender{
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
//pickerButton.titleLabel.text = TITLENAME;
//titleLabel.text= TITLENAME;
titleField.text = TITLENAME;
[titleLabel reloadInputViews];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[titlePicker removeConstraints:titlePicker];
[titlePicker removeFromSuperview];
}
#end
after reviewing your code i found one thing see below here is the problem
if(([textField tag] == 2)){
//something
return YES;
}
else if([textField tag] != 1){
return NO;
}
in else if block you keep return NO it means it doesn't take any input text , change that one to return YES it'l work.

Picker goes black, then crashes app (sometimes)

I have a number of text fields that offer a selection of pre defined values in the form of a picker view. Occasionally, usually after a lot of text boxes have been filled in, the picker goes black, then the app crashes.
I cant seem to reproduce the problem, it just happens occasionally...reported by some users. As ive picked up this code form someone else maybe I have missed something?
Here is the code for the custom class for the text box/pickers
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.touchEnabled = YES;
self.textField = nil;
self.editableTextField = nil;
__selectedValue = #"";
self.pickerView = nil;
self.button = nil;
self.textValue = nil;
self.otherSelected = NO;
self.backgroundColor = [UIColor clearColor];
self.userInteractionEnabled = YES;
self.values = [NSArray arrayWithObjects:#"Value1", #"Value2", #"Other", nil];
}
return self;
}
- (void)layoutSubviews
{
if (self.textField == nil) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 31.0f)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.font = [UIFont systemFontOfSize:12.0f];
UIPickerView *pickerView = [[UIPickerView alloc] init];
[pickerView sizeToFit];
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.showsSelectionIndicator = YES;
if (self.textValue != nil && ![self.textValue isEqualToString:#""]) {
textField.text = self.textValue;
int matchedIndex = -1;
int otherIndex = -1;
for (int i = 0; i < self.values.count; i++) {
NSString *value = [self.values objectAtIndex:i];
if ([value isEqualToString:#"Other"]) {
otherIndex = i;
}
if ([self.textValue isEqualToString:[self.values objectAtIndex:i]]) {
matchedIndex = i;
}
}
if (matchedIndex > -1) {
[pickerView selectRow:matchedIndex inComponent:0 animated:NO];
} else if (otherIndex > -1) {
[pickerView selectRow:otherIndex inComponent:0 animated:NO];
}
}
textField.inputView = pickerView;
self.pickerView = pickerView;
UIToolbar *accessoryView = [[UIToolbar alloc] init];
[accessoryView sizeToFit];
accessoryView.barStyle = UIBarStyleBlackOpaque;
accessoryView.tintColor = [UIColor grayColor];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(pickerDone:)];
self.doneButton = doneButton;
accessoryView.items = [NSArray arrayWithObjects:spacer, doneButton, nil];
textField.inputAccessoryView = accessoryView;
[self addSubview:textField];
self.textField = textField;
}
if (self.button == nil) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor clearColor];
button.frame = self.bounds;
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.button = button;
}
}
- (void)buttonPressed:(id)sender
{
if (self.fieldDelegate != nil) {
[self.fieldDelegate performSelector:#selector(fieldBeganEditing:) withObject:self];
}
if (self.otherSelected) {
self.doneButton.action = #selector(textFieldDone:);
self.textField.inputView = nil;
} else {
self.doneButton.action = #selector(pickerDone:);
self.textField.inputView = self.pickerView;
}
[self.textField becomeFirstResponder];
}
- (void)textFieldDone:(id)sender
{
LogCmd();
[self.textField resignFirstResponder];
self.textField.inputView = self.pickerView;
self.doneButton.action = #selector(pickerDone:);
[self.textField becomeFirstResponder];
}
- (void)pickerDone:(id)sender
{
LogCmd();
NSString *value = [self.values objectAtIndex:[self.pickerView selectedRowInComponent:0]];
if (!self.otherSelected) {
self.textField.text = value;
__selectedValue = value;
}
[self.textField resignFirstResponder];
}
/*- (void)setValues:(NSArray *)values
{
_values = values;
[self.pickerView reloadAllComponents];
}*/
#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
LogCmd();
}
#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
NSString *value = [self.values objectAtIndex:row];
if ([value isEqualToString:#"Other"]) {
self.otherSelected = YES;
self.textField.text = #"";
__selectedValue = #"";
[self.doneButton setAction:#selector(textFieldDone:)];
self.textField.inputView = nil;
[self.textField resignFirstResponder];
[self.textField becomeFirstResponder];
//[self.textField performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.2];
} else {
self.otherSelected = NO;
self.textField.text = value;
__selectedValue = value;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component
{
return [self.values objectAtIndex:row];
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return self.values.count;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}

Playing video in iPhone simulator with Media Player Framework

I am giving my entire code below if that helps anyway.....
#import "ContentViewController.h"
#import "ContentViewController.h"
#import "MediaPlayerViewController.h"
#import "TwitterViewController.h"
#import "YoutubeViewController.h"
#implementation ContentViewController
#synthesize imageView;
#synthesize imageView1;
#synthesize tableView;
#synthesize navigationController;
#synthesize toolBar;
#synthesize item;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - XMLParser Delegate
-(void)parseXMLFileAtURL:(NSString *)URL{
NSURL *xmlURL = [NSURL URLWithString:URL];
rssParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
NSLog(#"Parsed");
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"Found file and started parsing");
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSString *errorString = [NSString stringWithFormat:#"Unable to download feed from website (Error Code %i)", [parseError code]];
NSLog(#"Error parsing xml: %#", errorString);
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"channel"]) {
rssElement = [[NSMutableDictionary alloc]init];
title = [[NSMutableString alloc]init];
link = [[NSMutableString alloc]init];
description = [[NSMutableString alloc]init];
copyright = [[NSMutableString alloc]init];
}
}
-(void)parser: (NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"channel"]) {
[rssElement setObject:title forKey:#"title"];
[rssElement setObject:link forKey:#"link"];
[rssElement setObject:description forKey:#"description"];
[rssElement setObject:copyright forKey:#"copyright"];
[item addObject:[rssElement copy]];
NSLog(#"adding stories %#", title);
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"title"]) {
[title appendString:string];
}else if ([currentElement isEqualToString:#"link"]) {
[link appendString:string];
}else if ([currentElement isEqualToString:#"description"]) {
[description appendString:string];
}else if ([currentElement isEqualToString:#"copyright"]) {
[copyright appendString:string];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(#"all done");
NSLog(#"item array has %d items", [item count]);
[tableView reloadData];
NSLog(#"Finished Parsing");
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
/* Add Segmented Controller */
if (segmentedControl == nil) {
segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:#"Video", #"Images", #"Audio", nil]];
}
[segmentedControl setFrame:CGRectMake(55.0, 47.0, 180.0, 31.0)];
[segmentedControl setSegmentedControlStyle:UISegmentedControlStyleBar];
[segmentedControl setWidth:70.0 forSegmentAtIndex:0];
[segmentedControl setWidth:70.0 forSegmentAtIndex:1];
[segmentedControl setWidth:70.0 forSegmentAtIndex:2];
[segmentedControl addTarget:self
action:#selector(segmentClick:)
forControlEvents:UIControlEventValueChanged];
[segmentedControl setMomentary:YES];
// [[[segmentedControl subviews]objectAtIndex:0]setTintColor:[UIColor blackColor]];
[self.view addSubview:segmentedControl];
/* Add Image View */
imageView1.image = [UIImage imageNamed:#"Harry.png"];
/* Add Page Control */
pageControl = [[UIPageControl alloc] init];
pageControl.frame = CGRectMake(120.0, 250.0, 100.0 ,10.0);
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[self.view addSubview:pageControl];
/* Customize Table View */
tableView.backgroundColor = [UIColor clearColor];
imageView.image = [UIImage imageNamed:#"gradientBackground.png"];
item = [[NSMutableArray alloc]init];
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Video";
[self parseXMLFileAtURL:path];
[tableView reloadData];
NSLog(#"Returned %#", item);
}
headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 270.0, 300.0, 14.0)];
headerLabel.text = #"Latest Videos";
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:headerLabel];
}
/* Assign control to Segment Controller */
-(void)segmentClick:(UISegmentedControl *)segmentControl {
if (segmentControl.selectedSegmentIndex == 1){
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Image";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Images";
NSLog(#"Returned %#",item);
}
}
else if (segmentedControl.selectedSegmentIndex == 2){
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Audio";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Audios";
NSLog(#"Returned no items");
// [[[segmentedControl subviews]objectAtIndex:2]setTintColor:[UIColor blackColor]];
}
}
else {
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Video";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Videos";
NSLog(#"Returned %#", item);
}
// [[[segmentedControl subviews]objectAtIndex:0]setTintColor:[UIColor blackColor]];
}
}
#pragma mark Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"this is returned %#", item);
return item.count;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int feed = [indexPath indexAtPosition:[indexPath length] - 1];
cell.textLabel.text = [[item objectAtIndex:feed]objectForKey:#"title"];
cell.detailTextLabel.text = [[item objectAtIndex:feed]objectForKey:#"description"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *moviePath = [self.item objectAtIndex:indexPath.row];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
NSLog(#"Item has %#", movieURL);
playerController = [[MPMoviePlayerController alloc]initWithContentURL:movieURL];
[playerController play];
// MediaPlayerViewController *mediaView = [[MediaPlayerViewController alloc]initWithNibName:#"MediaPlayerViewController" bundle:nil];
// [self presentModalViewController:mediaView animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
shareAlert = [[UIActionSheet alloc]initWithTitle:#"Share to" delegate:self cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Facebook" otherButtonTitles:#"Twitter", nil];
[shareAlert showInView:self.view];
}
else if (buttonIndex == 1){
NSLog(#"button 2");
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
TwitterViewController *twitterController = [[TwitterViewController alloc]initWithNibName:#"TwitterViewController" bundle:nil];
[self presentModalViewController:twitterController animated:YES];
}
}
-(void)moviePlayBackDidFinish:(NSNotification *)notification{
MPMoviePlayerController *moviePlayerController = [notification object];
[moviePlayerController.view removeFromSuperview];
[moviePlayerController release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Changed didSelectRow method like following:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
moviePath = [[item objectAtIndex:indexPath.row]objectForKey:#"link"];
NSLog(#"moviepath has %#", moviePath);
movieURL = [NSURL URLWithString:moviePath];
NSLog(#"movieURL has %#", movieURL);
viewController = [[MPMoviePlayerViewController alloc]initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:viewController];
viewController.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[playerController play];
viewController = nil;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:viewController];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
viewController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:viewController];
if ([viewController respondsToSelector:#selector(setFullscreen:animated:)])
{
[viewController.view removeFromSuperview];
}
}
Now, on selecting any row a blank screen is coming and the application gets stuck there. Video is not played
Any help in this regard is appreciated.
Thanks in advance.
By looking at you code what i can tell you is that you dont have to reallocate your item object.
If you have allocated your item object somewhere in the class and stored the values in it then do not reallocate it again as you did here:
item = [[NSMutableArray alloc]init];
NSString *moviePath = [item objectAtIndex:indexPath.row];
by reallocating it you are allocating a new memory to it and in the new memory there is no objects present.
you are allocating new memory to your array by : item = [[NSMutableArray alloc]init]; . It means NO objects in it right now. And you are trying to access it by NSString *moviePath = [item objectAtIndex:indexPath.row]; where there is NO object at indexPath.row thats why it crashed.
There was actually nothing wrong with the code for playing video. The error was in the code for parsing and retrieving the rss feed which eventually was giving me wrong names of the videos. hence, videos were not playing.
The parsing code is Parsing attributes with same name but in different fields in iOS

pushViewController:detail not pushing detailView

I had my app navigating views perfectly. Now, for some reason that I can't figure out, my detailView is not presenting on the pushViewController:detail method in my modal view.
I cannot figure out why it's not working any more. Any help would be appreciated. Thanks.
Here's the method:
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
Here's the class code. I'm not sure if I need to pass in a navigationController with modalView:
//
// ModalView.m
// DiningLog
//
// Created by Eric Rea on 10/10/11.
// Copyright 2011 Avid. All rights reserved.
//
#import "ModalView.h"
#import "DetailView.h"
#implementation ModalView
#synthesize tableView, excersizeName, numSets, time, restTime, dateFormatter, rating, excersizeArray, plistArray, numberWithBool;
-(IBAction) cancel:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
-(IBAction) save:(id)sender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"ExcersizeList.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Excersizes" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// assign values
self.plistArray = [NSMutableArray arrayWithArray:[temp objectForKey:#"Excersizes"]];
NSLog(#"The contents of plistArray is%#", plistArray);
// set the variables to the values in the text fields
self.excersizeArray = [[NSMutableArray alloc] initWithCapacity:4];
[excersizeArray addObject:excersizeName];
[excersizeArray addObject:numSets];
[excersizeArray addObject:time];
[excersizeArray addObject:restTime];
[plistArray addObject:excersizeArray];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: plistArray, nil] forKeys:[NSArray arrayWithObjects: #"Excersizes", nil]];
NSString *error = nil;
// create NSData from dictionary
// NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistDict)
{
// write plistData to our Data.plist file
[plistDict writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
[self dismissModalViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tView {
// Return the number of sections.
return 1;
}
-(void)setObject:(id)object forNum:(int)num{
if(num == 0){
self.excersizeName = object;
NSLog(#"res %#", self.excersizeName);
}else if(num == 1){
self.numSets = object;
NSLog(#"res %#", self.numSets);
}else if(num == 2){
self.time = object;
NSLog(#"res %#", self.time);
}else if(num == 3){
self.restTime = object;
NSLog(#"res %#", self.restTime);
}else if(num == 4){
self.rating = [object floatValue];
}
[tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 5;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row == 0){
cell.textLabel.text = #"Excersize";
cell.detailTextLabel.text = excersizeName;
}
if(indexPath.row == 1){
cell.textLabel.text = #"Sets";
cell.detailTextLabel.text = numSets;
}
if(indexPath.row == 2){
cell.textLabel.text = #"Time";
cell.detailTextLabel.text = time;
}
if(indexPath.row == 3){
cell.textLabel.text = #"Rest";
cell.detailTextLabel.text = restTime;
}
if(indexPath.row == 4){
cell.textLabel.text = #"Rating";
cell.detailTextLabel.text = [NSString stringWithFormat:#"%f",rating];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (NSDateFormatter *)dateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return dateFormatter;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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];
}
#end
Have you debugged and checked that your navigationController isn't nil ?
I figured it out. I accidentally erased the method insertNewObject in my rootViewController. When I rewrote it, I forgot to add in ModalView * modal = [[ModalView alloc] init];. That was the problem.
Here's what the method looks like now that it's working:
- (void)insertNewObject {
ModalView * modal = [[ModalView alloc] init];
UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:modal];
[self presentModalViewController:controller animated:YES];
}