How do I stop a sound when a new sound button is pressed - xcode

I'm new to Xcode and I'm having an issue, if you click the sound buttons multiple times they overlap each other. How would I set my code so that if you click a button while a sound is playing it will stop the current sound playing and start the new one.
If you could post the code it would be much appreciated.
Thanks,
Dominick
Here is a copy of my current code:
#import "Sound3ViewController.h"
#implementation Sound3ViewController
-(IBAction)playnow:(id)sender;{
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"winning"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)play2:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"onadrug"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (void)dealloc
{
[super dealloc];
[sound release];
[super dealloc];
}
- (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 - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (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

I would suggest you to disallow playing the sound with a variable and schedule an action that allows it again after the duration of the file. Eg:
boolean allowed = true
-(IBAction)playnow:(id)sender
{
if (allowed) { // <--- ADD THIS
allowed = false;
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"winning"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
NSInvocation *invocation = [[NSInvocation alloc] init];
[invocation setTarget:self];
[invocation setSelector:#selector(allowPlaying)];
[NSTimer scheduledTimerWithTimeInterval:[sound duration] invocation:invocation repeats:NO];
} // <-- AND THIS
}
-(void)allowPlaying
{
allow = true;
}
Didn't test it since just wrote on the fly but you've got the general idea..

I'm new to objC also, so I'm not sure this is correct, but try this:
#import "Sound3ViewController.h"
#implementation Sound3ViewController
-(IBAction)playnow:(id)sender;{
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"winning"
ofType:#"mp3"]];
// NEW STUFF
if (sound) {
if ([sound playing]) {
[sound stop];
}
[sound release];
}
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)play2:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"onadrug"
ofType:#"mp3"]];
if (sound) {
if ([sound playing]) {
[sound stop];
}
[sound release];
}
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (void)dealloc
{
[super dealloc];
if (sound) {
[sound release];
}
}
- (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 - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (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

// in .h file
#import "AVFoundation/AVAudioPlayer.h"
//set delegate
#interface SamplesoundViewController : UIViewController <AVAudioPlayerDelegate>{
AVAudioPlayer *player1;
AVAudioPlayer *player2;
...
...
}
#property (nonatomic, retain) AVAudioPlayer *player1;
#property (nonatomic, retain) AVAudioPlayer *player2;
-(IBAction)soundfirst;
-(IBAction)soundsecond;
-(IBAction)Newmethodname;
// in .m file
#implementation SamplesoundViewController
#synthesize player1,player2;
-(IBAction)soundfirst{
NSString *path = [[NSBundle mainBundle] pathForResource:#"soundfilefirst" ofType:#"mp3"];
player1=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
player1.delegate=self;
[player1 play];
[self performSelector:#selector(soundsecond) withObject:nil afterDelay:0.90];
}
-(IBAction)soundsecond{
[player1 stop];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Soundfilesecond" ofType:#"mp3"];
player2=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
player2.delegate=self;
[player2 play];
[self performSelector:#selector(Newmethodname) withObject:nil afterDelay:1];
}
-(IBAction)Newmethodname{
[player2 stop];
//write your code here
}

Related

no visible #interface for 'UIImagePickerController

So my code says
no visible #interface for UIImagePicker Controller
I am using a Tab View Controller
My code for my FirstViewController.m is
#import "FirstViewController.h"
#interface FirstViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *bailey;
UIImagePickerController *baileys;
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction)takePhoto;
- (IBAction)chooseExisting;
#end
#implementation FirstViewController
- (IBAction)takePhoto {
bailey = [[UIImagePickerController alloc]init];
bailey.delegate = self;
[bailey setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:bailey animated:YES completion:NULL];
}
- (IBAction)chooseExisting {
baileys = [[UIImagePickerController alloc] init];
baileys.delegate = self;
[baileys setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:baileys animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)bailey {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)ShareFB {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[slComposeViewController addImage:[UIImage imageNamed:#"image"]];
[slComposeViewController addURL:[NSURL URLWithString:#"http://www.agfg.com.au"]];
[self presentViewController:slComposeViewController animated:YES completion:NULL];
//I borrowed these lines of code from http://www.bit.ly/174eqjy
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingString:#"upload.png"];
NSString *upLoad = [documentsDirectory stringByAppendingString:#"upload.png"];
NSData *myData = [[NSData alloc]initWithContentsOfFile:appFile];
//Here is the line that fails
[bailey addAttachmentData:myData mimeType:#"image/png" fileName:#"upload"];
//Up to here are the borrowed code lines.
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Facebook Account Detected" message:#"There are no Facebook Accounts Detected. You can configure them in Settings." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
}}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And my code for my FirstViewController.h is
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#interface FirstViewController : UIViewController {SLComposeViewController *slComposeViewController;
UIImage *upLoad;}
- (IBAction)ShareFB;
#end
My app is designed to Take a photo and display the photo (and it does that) and then save that image to the local documents folder on the app (which I got from another post) and then specify that image to upload to Facebook (which I have)
All that works except the saving to a local documents.
If you need to store file in documents directory, use like this,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Images"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *imageFilePath = [NSString stringWithFormat:#"%#/%#",dataPath,#"upload.png"];
UIImage *image = [UIImage imageNamed:#"image"]; //Here place your image
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageData writeToFile:imageFilePath atomically:YES];
If you need to attach image in facebook, use this statement,
[slComposeViewController
addAttachmentData:UIImagePNGRepresentation(image, 1) mimeType:#"image/png" fileName:#"upload.png"];
With the help of Karthika, and his facebook upload code, I was typing it in when I realised that I did not need to implement local documents saving.
Facebook let me add the image in without saving it.
Thanks though Karthika, I could not have done it without you.

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];

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;
}

How to call registerForDraggedTypes in NSViewController?

I have a MainViewController with a splitview in it. Next I have two viewcontroller to control each of the views in the splitview. I want to be able to drag and drop a file in one of those views.
But I can't seem to get the dragging to work? There's no "plus-sign" on the file when dragged to the view and dropping it doesn't do anything either.
What am I doing wrong?
First here's MainViewController.m
fileViewController = [[FileViewController alloc] initWithNibName:#"FileViewController" bundle:nil];
terminalViewController = [[TerminalViewController alloc] initWithNibName:#"TerminalViewController" bundle:nil];
[splitView replaceSubview:[[splitView subviews] objectAtIndex:0] with:[fileViewController view]];
[splitView replaceSubview:[[splitView subviews] objectAtIndex:1] with:[terminalViewController view]];
Next, my code to handle the dragging in the FileViewController
#dynamic isHighlighted;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
NSLog(#"registering");
[self.view registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
}
return self;
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
NSLog(#"[%# %#]", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
NSPasteboard *pboard = [sender draggingPasteboard];
if ([[pboard types] containsObject:NSFilenamesPboardType]) {
NSArray *paths = [pboard propertyListForType:NSFilenamesPboardType];
for (NSString *path in paths) {
NSError *error = nil;
NSString *utiType = [[NSWorkspace sharedWorkspace]
typeOfFile:path error:&error];
if (![[NSWorkspace sharedWorkspace]
type:utiType conformsToType:(id)kUTTypeFolder]) {
[self setHighlighted:NO];
return NSDragOperationNone;
}
}
}
[self setHighlighted:YES];
return NSDragOperationEvery;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender {
[self setHighlighted:NO];
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
[self setHighlighted:NO];
return YES;
}
- (void)concludeDragOperation:(id )sender {
[self.view setNeedsDisplay:YES];
} // end concludeDragOperation
- (BOOL)isHighlighted {
return isHighlighted;
}
- (void)setHighlighted:(BOOL)value {
isHighlighted = value;
[self.view setNeedsDisplay:YES];
}
- (void)drawRect:(NSRect)frame {
[self.view drawRect:frame];
if (isHighlighted) {
[NSBezierPath setDefaultLineWidth:6.0];
[[NSColor keyboardFocusIndicatorColor] set];
[NSBezierPath strokeRect:frame];
}
}
I didn't seem to fix it, and because no one gave me any answers, I fixed it by making an NSView subclass and adding it to my viewcontroller like this.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
draggable = [[DragView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
[[self view] addSubview:draggable];
}
return self;
}
I've never done OS X programming, but the problem is that since you're registering self.view to receive drag and drop, your self.view should handle the drag and drop operations and not your view controller. So you're correct in subclassing NSView to DragView, and you should pass the drag operations back to the view controller.
Also, I believe - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender should be implemented.

How to find your current location with CoreLocation

I need to find my current location with CoreLocation, I tried multiple methods but so far my CLLocationManager has only returned 0's.. (0.000.00.000).
Here's my code (updated to work):
Imports:
#import <CoreLocation/CoreLocation.h>
Declared:
IBOutlet CLLocationManager *locationManager;
IBOutlet UILabel *latLabel;
IBOutlet UILabel *longLabel;
Functions:
- (void)getLocation { //Called when needed
latLabel.text = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.latitude];
longLabel.text = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.longitude];
}
- (void)viewDidLoad {
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
You can find your location using CoreLocation like this:
import CoreLocation:
#import <CoreLocation/CoreLocation.h>
Declare CLLocationManager:
CLLocationManager *locationManager;
Initialize the locationManager in viewDidLoad and create a function that can return the current location as an NSString:
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
And calling the deviceLocation function will return the location as expected:
NSLog(#"%#", [self deviceLocation]);
This is just an example. Initializing CLLocationManager without the user being ready for it isn't a good idea. And, of course, locationManager.location.coordinate can be used to get latitude and longitude at will after CLLocationManager has been initialized.
Don't forget to add the CoreLocation.framework in your project settings under the Build Phases tab (Targets->Build Phases->Link Binary).
With CLLocationManager you don't necessary get the location information immediately. The GPS and other devices that obtain location information might not be initialized. They can take a while before they have any information. Instead you need to create a delegate object that responds to locationManager:didUpdateToLocation:fromLocation: and then set it as the delegate of the location manager.
see here
Here you can show current location with annotation details
in ViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
//My
#import <MapKit/MapKit.h>
#import <MessageUI/MFMailComposeViewController.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,MFMailComposeViewControllerDelegate>
{
IBOutlet UILabel *lblLatitiude;
IBOutlet UILabel *lblLongitude;
IBOutlet UILabel *lblAdress;
}
//My
#property (nonatomic, strong) IBOutlet MKMapView *mapView;
-(IBAction)getMyLocation:(id)sender;
#end
in ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
CLLocationManager *locationManager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}
#synthesize mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *defaultsDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"pradipvdeore#gmail.com", #"fromEmail",
#"pavitrarupani89#gmail.com", #"toEmail",
#"smtp.gmail.com", #"relayHost",
#"mobileapp.qa#gmail.com", #"login",
#"mobile#123", #"pass",
[NSNumber numberWithBool:YES], #"requiresAuth",
[NSNumber numberWithBool:YES], #"wantsSecure", nil];
[userDefaults registerDefaults:defaultsDictionary];
self.mapView.delegate=self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Custom Methods
-(IBAction)getMyLocation:(id)sender{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
lblLongitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lblLatitiude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
lblAdress.text = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = currentLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
[self.mapView addAnnotation:point];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
//My
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"loc"];
annotationView.canShowCallout = YES;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return annotationView;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
[self getSignScreenShot];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"My Subject"];
[controller setMessageBody:#"Hello there." isHTML:NO];
if (controller) [self presentModalViewController:controller animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(#"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
//-----------------------------------------------------------------------------------
//This methos is to take screenshot of map
//-----------------------------------------------------------------------------------
-(UIImage *)getSignScreenShot
{
CGRect rect = CGRectMake(self.mapView.frame.origin.x,self.mapView.frame.origin.y-50,self.mapView.frame.size.width+60,self.mapView.frame.size.height+15);
UIGraphicsBeginImageContextWithOptions(self.mapView.frame.size, NO, 1.0);
[self.mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], rect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
return newImage;
}

Resources