UILabels animation called by delegate/protocols structure - delegates

I want to use a little animation for my labels.
If I try to call this animation from a IBAction button or ViewDidLoad and all work correctly.
- (void)animateLabelShowText:(NSString*)newText characterDelay:(NSTimeInterval)delay
{
[self.myLabel setText:#""];
for (int i=0; i<newText.length; i++)
{
dispatch_async(dispatch_get_main_queue(),
^{
[self.myLabel setText:[NSString stringWithFormat:#"%#%C", self.myLabel.text, [newText characterAtIndex:i]]];
});
[NSThread sleepForTimeInterval:delay];
}
}
called by:
-(void) doStuff
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
^{
[self animateLabelShowText:#"Hello Vignesh Kumar!" characterDelay:0.5];
});
}
But if I put this method in a protocol and I try to call it from for example a delegate nothing appears. There's probably I missing something in the GDC (Grand Central Dispatch) logics:
...
if ([_myDelegate respondsToSelector:#selector(doStuff:)])
{
NSLog(#" Yes I'm in and try to execute doStuff..");
[_myDelegate doStuff]; // NOTHING TO DO
}
...
The same situation happened when I change my function doStuff with any similar function like:
-(void)typingLabel:(NSTimer*)theTimer
{
NSString *theString = [theTimer.userInfo objectForKey:#"string"];
int currentCount = [[theTimer.userInfo objectForKey:#"currentCount"] intValue];
currentCount ++;
NSLog(#"%#", [theString substringToIndex:currentCount]);
[theTimer.userInfo setObject:[NSNumber numberWithInt:currentCount] forKey:#"currentCount"];
if (currentCount > theString.length-1) {
[theTimer invalidate];
}
[self.myLabel setText:[theString substringToIndex:currentCount]];
}
called by
-(void) doStuff
{
NSString *string =#"Risa Kasumi & Yuma Asami";
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:string forKey:#"string"];
[dict setObject:#0 forKey:#"currentCount"];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(typingLabel:) userInfo:dict repeats:YES];
[timer fire];
}

I've solved using NSNotificationCenter in my delegate file .m
in viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(makeEffectOnMyLabel:) name:#"lblUpdate" object:nil];
in my protocol function :
dispatch_async( dispatch_get_main_queue(),
^{
...I've populated a dictionary userInfo with my vars
[[NSNotificationCenter defaultCenter] postNotificationName:#"lblUpdate" object:nil userInfo:userInfo];
});
in a function created to prepare typingLabel
-(void) makeEffectOnMyLabel:(NSNotification *) notification
{
..changes between dictionaries to prepare typingLabel..
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSDictionary* userInfo = [notification userInfo];
[dict setObject:[userInfo objectForKey:#"myRes"] forKey:#"myRes"];
[dict setObject:[userInfo objectForKey:#"myType"] forKey:#"myType"];
[dict setObject:[userInfo objectForKey:#"frase"] forKey:#"frase"];
[dict setObject:#0 forKey:#"currentCount"];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(typingLabel:) userInfo:dict repeats:YES];
[timer fire];
}
Now all work correct.

Related

How can I run a NSTask in the background and show the results in a modal NSWindow while running

I would like to execute a command with NSTask, and be able to see the progress in a modal window. For example if I execute 'ls -R /' i would like to see the chunks appearing in a NSTextView.
I came up with the following, and everything works fine, except the update part. The task get executed (with the spinning beachbal) and when it is finished i see the result appear in the textview.
#interface ICA_RunWindowController ()
#property (strong) IBOutlet NSTextView* textResult;
#property (strong) IBOutlet NSButton* buttonAbort;
#property (strong) IBOutlet NSButton* buttonOK;
- (IBAction) doOK:(id) sender;
- (IBAction) doAbort:(id) sender;
#end
#implementation ICA_RunWindowController {
NSTask * executionTask;
id taskObserver;
NSFileHandle * errorFile;
id errorObserver;
NSFileHandle * outputFile;
id outputObserver;
}
#synthesize textResult,buttonAbort,buttonOK;
- (IBAction)doOK:(id)sender {
[[self window] close];
[NSApp stopModal];
}
- (IBAction)doAbort:(id)sender {
[executionTask terminate];
}
- (void) taskCompleted {
NSLog(#"Task completed");
[[NSNotificationCenter defaultCenter] removeObserver:taskObserver];
[[NSNotificationCenter defaultCenter] removeObserver:errorObserver];
[[NSNotificationCenter defaultCenter] removeObserver:outputObserver];
[self outputAvailable];
[self errorAvailable];
executionTask = nil;
[buttonAbort setEnabled:NO];
[buttonOK setEnabled:YES];
}
- (void) appendText:(NSString *) text inColor:(NSColor *) textColor {
NSDictionary * makeUp = [NSDictionary dictionaryWithObject:textColor forKey:NSForegroundColorAttributeName];
NSAttributedString * extraText = [[NSAttributedString alloc] initWithString:text attributes:makeUp];
[textResult setEditable:YES];
[textResult setSelectedRange:NSMakeRange([[textResult textStorage] length], 0)];
[textResult insertText:extraText];
[textResult setEditable:NO];
[textResult display];
}
- (void) outputAvailable {
NSData * someData = [outputFile readDataToEndOfFile];
if ([someData length] > 0) {
NSLog(#"output Available");
NSString * someText = [[NSString alloc] initWithData:someData encoding:NSUTF8StringEncoding];
[self appendText:someText inColor:[NSColor blackColor]];
}
}
- (void) errorAvailable {
NSData * someData = [errorFile readDataToEndOfFile];
if ([someData length] > 0) {
NSLog(#"Error Available");
NSString * someText = [[NSString alloc] initWithData:someData encoding:NSUTF8StringEncoding];
[self appendText:someText inColor:[NSColor redColor]];
}
}
- (void) runCommand:(NSString *) command {
// make sure all views are initialized
[self showWindow:[self window]];
// some convience vars
NSArray * runLoopModes = #[NSDefaultRunLoopMode, NSRunLoopCommonModes];
NSNotificationCenter * defCenter = [NSNotificationCenter defaultCenter];
// create an task
executionTask = [[NSTask alloc] init];
// fill the parameters for the task
[executionTask setLaunchPath:#"/bin/sh"];
[executionTask setArguments:#[#"-c",command]];
// create an observer for Termination
taskObserver = [defCenter addObserverForName:NSTaskDidTerminateNotification
object:executionTask
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note)
{
[self taskCompleted];
}
];
// Create a pipe and a filehandle for reading errors
NSPipe * error = [[NSPipe alloc] init];
[executionTask setStandardError:error];
errorFile = [error fileHandleForReading];
errorObserver = [defCenter addObserverForName:NSFileHandleDataAvailableNotification
object:errorFile
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note)
{
[self errorAvailable];
[errorFile waitForDataInBackgroundAndNotifyForModes:runLoopModes];
}
];
[errorFile waitForDataInBackgroundAndNotifyForModes:runLoopModes];
// Create a pipe and a filehandle for reading output
NSPipe * output = [[NSPipe alloc] init];
[executionTask setStandardOutput:output];
outputFile = [output fileHandleForReading];
outputObserver = [defCenter addObserverForName:NSFileHandleDataAvailableNotification
object:outputFile
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note)
{
[self outputAvailable];
[outputFile waitForDataInBackgroundAndNotifyForModes:runLoopModes];
}
];
[outputFile waitForDataInBackgroundAndNotifyForModes:runLoopModes];
// start task
[executionTask launch];
// show our window as modal
[NSApp runModalForWindow:[self window]];
}
My question: Is it possible to update the output while the task is running? And, if yes, how could I achieve that?
A modal window runs the run loop in NSModalPanelRunLoopMode, so you need to add that to your runLoopModes.
You should not be getting the spinning beach ball. The cause is that you're calling -readDataToEndOfFile in your -outputAvailable and -errorAvailable methods. Given that you're using -waitForDataInBackgroundAndNotifyForModes:, you would use the -availableData method to get what data is available without blocking.
Alternatively, you could use -readInBackgroundAndNotifyForModes:, monitor the NSFileHandleReadCompletionNotification notification, and, in your handler, obtain the data from the notification object using [[note userInfo] objectForKey:NSFileHandleNotificationDataItem]. In other words, let NSFileHandle do the work of reading the data for you.
Either way, though, once you get the end-of-file indicator (an empty NSData), you should not re-issue the ...InBackgroundAndNotifyForModes: call. If you do, you'll busy-spin as it keeps feeding you the same end-of-file indicator over and over.
It shouldn't be necessary to manually -display your text view. Once you fix the blocking calls that were causing the spinning color wheel cursor, that will also allow the normal window updating to happen automatically.

Saving data to an existing plist

I am working on a project that has a simple tableview with detail view.
Data source is a plist. I am trying to allow user input to be saved into the plist and shown in tableview. i have created a add view controller which gets presented and dismissed modally and has two text fields which allow the user to add the name of the city and name of the states, also a text field to input description.
Problem: how to save this data to my existing plist and show it in the tableview. Here is my code for the table view:
#implementation TableViewController
#synthesize content, searchResults;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
content = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"]];
}
- (IBAction)add;
{
AddViewController* controller = [[AddViewController alloc] init];
[self presentViewController:controller animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.searchResults count];
} else {
return [self.content count];
}
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat: #"SELF['city'] BEGINSWITH[c] %# ", searchText];
searchResults = [[content filteredArrayUsingPredicate:resultPredicate] retain];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier] autorelease];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [[searchResults objectAtIndex:indexPath.row] valueForKey:#"city"];
cell.detailTextLabel.text = [[searchResults objectAtIndex:indexPath.row] valueForKey:#"state"];
cell.imageView.image = [UIImage imageNamed:[[self.searchResults objectAtIndex:indexPath.row] valueForKey:#"cityImage"]];
} else {
cell.textLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:#"city"];
cell.detailTextLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:#"state"];
cell.imageView.image = [UIImage imageNamed:[[self.content objectAtIndex:indexPath.row] valueForKey:#"cityImage"]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
[self performSegueWithIdentifier: #"showDetails" sender: self];
}
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showDetails"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *DVC = [segue destinationViewController];
if ([self.searchDisplayController isActive]) {
DVC.cityImageString = [[searchResults objectAtIndex:indexPath.row] valueForKey:#"cityImage"];
DVC.cityTextString = [[searchResults objectAtIndex:indexPath.row] valueForKey:#"cityText"];
DVC.cityNameString = [[searchResults objectAtIndex:indexPath.row] valueForKey:#"city"];
DVC.stateNameString = [[searchResults objectAtIndex:indexPath.row] valueForKey:#"state"];
} else {
DVC.cityImageString = [[self.content objectAtIndex:indexPath.row] valueForKey:#"cityImage"];
DVC.cityTextString = [[self.content objectAtIndex:indexPath.row] valueForKey:#"cityText"];
DVC.cityNameString = [[self.content objectAtIndex:indexPath.row] valueForKey:#"city"];
DVC.stateNameString = [[self.content objectAtIndex:indexPath.row] valueForKey:#"state"];
}
}
}
and here is the code for addViewController.h:
#interface AddViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
IBOutlet UITextField *cityTextField;
IBOutlet UITextField *stateTextField;
IBOutlet UITextView *cityDescription;
UIImagePickerController* imagePicker;
}
#property (nonatomic, copy) NSString* name;
#property (nonatomic, copy) NSString* description;
#property (nonatomic, strong) UIImage* image;
#property (nonatomic, retain) IBOutlet UINavigationBar* navigationBar;
#property (nonatomic, strong) UITextField *cityTextField;
#property (nonatomic, strong) UITextField *stateTextField;
#property (nonatomic, strong) UITextView *cityDescription;
#property (nonatomic, strong) IBOutlet UIButton* choosePhotoButton;
#property (nonatomic, strong) IBOutlet UIButton* takePhotoButton;
- (IBAction)save;
- (IBAction)cancel;
- (IBAction)choosePhoto;
- (IBAction)takePhoto;
#end
and at last the add view controller .m
#implementation AddViewController
#synthesize cityTextField, stateTextField, cityDescription;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)save
{
// Make sure the user has entered at least a recipe name
if (self.cityTextField.text.length == 0)
{
UIAlertView* alertView = [[UIAlertView alloc]
initWithTitle:#"Whoops..."
message:#"Please enter a city name"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
return;
}
if (self.stateTextField.text.length == 0)
{
UIAlertView* alertView = [[UIAlertView alloc]
initWithTitle:#"Whoops..."
message:#"Please enter a city name"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
return;
}
// Make sure the user has entered at least a recipe name
if (self.cityDescription.text.length == 0)
{
UIAlertView* alertView = [[UIAlertView alloc]
initWithTitle:#"Whoops..."
message:#"Please enter city description"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
return;
}
self.name = self.cityTextField.text;
self.name = self.stateTextField.text;
self.description = self.cityDescription.text;
if ([[self parentViewController] respondsToSelector:#selector(dismissViewControllerAnimated:)]){
[[self parentViewController] dismissViewControllerAnimated:YES completion:nil];
} else {
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
}
}
- (IBAction)cancel {
{
if ([[self parentViewController] respondsToSelector:#selector(dismissModalViewControllerAnimated:)]){
[[self parentViewController] dismissViewControllerAnimated:YES completion:nil];
} else {
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
}
}
}
- (IBAction)choosePhoto
{
// Show the image picker with the photo library
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (IBAction)takePhoto {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([cityDescription isFirstResponder] && [touch view] != cityDescription) {
[cityDescription resignFirstResponder];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[cityTextField resignFirstResponder];
[stateTextField resignFirstResponder];
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
// We get here when the user has successfully picked an image.
// Put the image in our property and set it on the button.
if (imagePicker) {
self.image = [info objectForKey:UIImagePickerControllerEditedImage];
[self.choosePhotoButton setImage:self.image forState:UIControlStateNormal];
} else {
if (picker) {
self.image = [info objectForKey:UIImagePickerControllerEditedImage];
[self.takePhotoButton setImage:self.image forState:UIControlStateNormal];
}
}
[self dismissViewControllerAnimated:YES completion:nil];
[imagePicker release];
imagePicker = nil;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
[imagePicker release];
imagePicker = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
i know there are tons of almost similar questions and believe me i have looked at so many of them and i think i am hitting the wall with this one and i cant think of a proper way to do this. it may be so simple but for the life of me i cant figure this out and thats why i am trying to ask for help. i truly appreciate any help i can get. if needs be i can place the sample project on git hub for ease of access. also the project is built in ios 6 and the latest Xcode.
P.S. here is the link to the project on git hub: https://github.com/AdrianPhillips/TableSearch
I can't find your code that do the actual "save" work. I guess it should be in the UIAlertView delegate,right ? And you did not tell us what's your problem. Following code maybe what's you seeking.
[content writeToFile:filePath atomically:YES]
Another reminder is: you should NOT save the plist back to main bundle, save it to Documents or Cache or other folder.
Just as every one has pointed out you can not write to the plist that is in your main bundle. You need to copy it from the bundle to your application document directory. Then you can just init from and write to the path in your documents directory. The other issue you have, is that nothing is communicating the new data from the AddViewController back to the TableViewController. You should create a protocol and delegate for your AddViewController.
For all the gore details see my pull request on GitHub.
https://github.com/GayleDDS/TableSearch.git
You have to copy the plist to the Documents folder first. You can't edit it into the original app folder. You can use this class to do this:
- (void) CreatePlistCopyInDocuments:(NSString *)plistName {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:plistName];
success = [fileManager fileExistsAtPath:writablePath];
if (success) {
return;
}
// The writable file does not exist, so copy from the bundle to the appropriate location.
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:plistName];
success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable file with message '%#'.", [error localizedDescription]);
}
}
You have just to pass the plist name to it.
Then you have to load it into some NSMutableDictionary like this:
NSString *documents = [NSHomeDirectory() stringByAppendingString:#"/Documents"];
NSString *plistInDocuments = [documents stringByAppendingPathComponent:#"UserData.plist"];
NSMutableDictionary *plistData = [[NSMutableDictionary alloc]initWithContentsOfFile:plistInDocuments];
After you have updated the values for the dictionary, you have to write the file back to the documents like this:
[plistData writeToFile:plistInDocuments atomically:YES];

close uitableview and reload another uitableview

i have problem.
I have CityViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
TheatreController *tmpTheatreController = [storyboard instantiateViewControllerWithIdentifier:#"TheatreController"];
NSString *cityView = [[self.arrayCity objectAtIndex:indexPath.row] valueForKey:#"idCity"];
tmpTheatreController.cityView = cityView;
//[self.navigationController pushViewController:tmpTheatreController animated:YES];
[tmpTheatreController.tableView reloadData];
[self.delegate citiesViewControllerCancel:self];
}
When i select the city pass correctly the "idCity" in TheatreController.m
...
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"SelectCity"])
{
UINavigationController *nc = segue.destinationViewController;
CityViewController *mvc = [[nc viewControllers] objectAtIndex:0];
mvc.delegate = self;
}
}
...
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *webUrl = #"http://localhost:3000/theatres?city=";
webUrl = [webUrl stringByAppendingFormat:#"%#", cityView];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:webUrl]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES]; });
}
- (void)fetchedData:(NSData *)responseData {
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions error:nil];
NSMutableArray *theatreTMP = [[NSMutableArray alloc] initWithCapacity:[json count]];
int i = 0;
for (id object in [json valueForKeyPath:#"response.name"]) {
Theatres *t = [[Theatres alloc] init];
NSLog(#"JSON: %#", [[json valueForKeyPath:#"response.name"] objectAtIndex:i]);
t.theatre = [[json valueForKeyPath:#"response.name"] objectAtIndex:i];
t.idTheatre = [[json valueForKeyPath:#"response.id"] objectAtIndex:i];
[theatreTMP addObject:t];
i++;
}
self.arrayTheatre = [theatreTMP copy];
[self.tableView reloadData];
}
I have correctly the response of the server and all parameter are correct, but the problem i have with reloadData of the tableView main![enter image description here][1]. I dont see the update table.
HELP ME thanks
i have resolved with this solution
In the CityViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cityView = [[self.arrayCity objectAtIndex:indexPath.row] valueForKey:#"idCity"];
[self.delegate performSelector:#selector(reloadTable:) withObject:cityView];
[self.delegate citiesViewControllerCancel:self];
}
and in the TheatreTableView.m
- (void) callServer:(NSString *)idCity {
NSString *webUrl = #"http://localhost:3000/theatres?city=";
webUrl = [webUrl stringByAppendingFormat:#"%#", idCity];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:webUrl]];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];});
}
....
- (void) reloadTable:(id)idCity
{
[self callServer:idCity];
}
Thanks

mpmovieplayercontroller disappears as soon as it starts

When I click “play movie” the mpmovieplayer presents itself for half a second and I see it’s loading movie and the controls are there, but then it returns to main screen without playing the video.
How do I fix this?
Edit:
I have changed code and now the player stays up but is stuck on loading, it doesn’t play movie.
IS the problem: not preparing the movie for play? Or not stopping movie in background and then restarting it?
#import "ViewController.h"
#implementation ViewController
#synthesize moviePlayer;
-(IBAction)grabVid:(id)sender;
{
[self presentModalViewController:imagePicker animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[imagePicker setDelegate:self];
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.mediaTypes =
[UIImagePickerController availableMediaTypesForSourceType:
imagePicker.sourceType];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
{
[imagePicker dismissModalViewControllerAnimated:YES];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
//[imagePicker dismissModalViewControllerAnimated:YES];
}
-(IBAction)playMovie:(id)sender
{
NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self.view addSubview:playercontroller.moviePlayer.view];
[playercontroller.moviePlayer setFullscreen:YES animated:YES];
playercontroller.moviePlayer.shouldAutoplay = NO;
[self presentMoviePlayerViewControllerAnimated:playercontroller];
playercontroller.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playercontroller.moviePlayer play];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:playercontroller.moviePlayer];
}
- (void)moviePlaybackComplete:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[moviePlayerController.view removeFromSuperview];
//[playercontroller.moviePlayer release];
}
- (void)dealloc {
//[super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
-(IBAction) playVideo
{
NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
moviePlayer.initialPlaybackTime = 0;
[self presentMoviePlayerViewControllerAnimated:playercontroller];
playercontroller.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playercontroller.moviePlayer play];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
// playercontroller = nil;
}

NSTimer wont stop [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
NSTimer doesn't stop
I am having a hard time stopping my timer, witch pings to my server.
I already searched for other answers here and on other places, but i can`t seem to find where i have gone wrong.
I decided to make an example code with the same idea, but, you click a button the timer starts, you click another the timer ends, and it worked the way it should. Please don't mind if i did something wrong (other than the timer part) i'm new in this. All i want to know is why won`t it stop..
Thanks in advance.
Connection.h
#import <Foundation/Foundation.h>
#interface Connection : NSObject
{
NSString *urlString;
NSURL *url;
NSMutableURLRequest *request;
NSURLConnection *connection;
NSURLResponse *response;
NSMutableData *receivedData;
NSData *responseData;
NSError *error;
NSTimer *timer;
}
#property (nonatomic, retain) NSTimer *timer;
-(BOOL)authenticateUser:(NSString *)userName Password:(NSString *)password;
-(BOOL)checkConnection;
-(void)ping:(NSTimer *)aTimer;
-(void)logout;
-(void)timerStart;
-(void)timerStop;
#end
Connection.m
#import "Connection.h"
#import "Parser.h"
#import "Reachability.h"
#import "TBXML.h"
#implementation Connection
#synthesize timer;
-(BOOL) authenticateUser:(NSString *)userName Password:(NSString *)password
{
BOOL success;
urlString = [[NSString alloc] initWithFormat:#"my/server/address/login"];
url =[[NSURL alloc] initWithString:urlString];
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
error = [[NSError alloc] init];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[responseData retain];
NSString *tempString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *tempDict= [[NSMutableDictionary alloc] init];
if (request)
{
Parser *parser = [[Parser alloc] init];
tempDict = [parser readXMLString:tempString];
for (id key in tempDict)
{
NSLog(#"%# is %#",key,[tempDict objectForKey:key]);
}
if ([[tempDict objectForKey:#"login"] isEqualToString:#"true"] )
{
success = YES;
self.timerStart;
}
else
{
success = NO;
}
}
[urlString release];
[url release];
[error release];
[responseData release];
[tempString release];
return success;
}
-(void)logout
{
self.timerStop;
}
-(void)ping:(NSTimer *)aTimer;
{
urlString = [[NSString alloc] initWithFormat:#"my/server/address"];
url =[[NSURL alloc] initWithString:urlString];
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSLog(#"ping");
[urlString release];
[url release];
}
-(BOOL)checkConnection
{
Reachability *reachability = [Reachability reachabilityWithHostName:#"http://my/server/address"];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
return NO;
}
else
{
return YES;
}
}
-(void)timerStart
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(ping:) userInfo:nil repeats:YES];
}
-(void)timerStop
{
[self.timer invalidate];
self.timer = nil;
}
#end
In timerStart you just replace whatever is in the timer property. If you start a second timer without stopping the first one, it will run forever. So timerStart should first call timerStop before creating a new one (and should probably have a new name then as it would be silly to call timerStop from timerStart).
Use [self timerStop]; using dot syntax is ONLY for properties (and will generate a warning if you don't), not calling a method in the way you're doing it.
Edit: This won't fix your problem, but doing it the way you are is very bad coding practice
-(void)timerStart
{
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(ping:) userInfo:nil repeats:YES];
}

Resources