How to call registerForDraggedTypes in NSViewController? - macos

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.

Related

Drag Drop delegate for NSView could not set an attribute

I am using NSView delegate to read the dragged excel values. For this I have subclassed NSView. My code is like-
#interface SSDragDropView : NSView
{
NSString *textToDisplay;
}
#property(nonatomic,retain) NSString *textToDisplay; // setters/getters
#synthesize textToDisplay;// setters/getters
#implementation SSDragDropView
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
[self setNeedsDisplay: YES];
return NSDragOperationGeneric;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender{
[self setNeedsDisplay: YES];
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
[self setNeedsDisplay: YES];
return YES;
}
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender {
NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
if ([[[draggedFilenames objectAtIndex:0] pathExtension] isEqual:#"xls"]){
return YES;
} else {
return NO;
}
}
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender{
NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
NSURL *url = [NSURL fileURLWithPath:[draggedFilenames objectAtIndex:0]];
NSString *textDataFile = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil]; //This text is the original excel text and its getting displayed.
[self setTextToDisplay:textDataFile];
}
I am setting the textDataFile value to a string attribute of that class. Now I am using SSDragDropView attribute value in some other class like-
SSDragDropView *dragView = [SSDragDropView new];
NSLog(#"DragView Value is %#",[dragView textToDisplay]);
But I am getting null each time. Is it like I can not set an attribute value in those delegate methods?
The above problem can be resolved just by declaring a global variable in your SSDragDropView.h class.
#import <Cocoa/Cocoa.h>
NSString *myTextToDisplay;
#interface SSDragDropView : NSView
{
The same can be set inside the desired delegate method
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender {
// .... //Your Code
NSString *textDataFile = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
myTextToDisplay = textDataFile;
// .... //Your Code
}
:)
Add
[dragView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
NSPasteboard *pboard = [sender draggingPasteboard];
NSArray *paths = [pboard propertyListForType:NSFilenamesPboardType];
NSLog(#"%#",paths);
[self setNeedsDisplay: YES];
return NSDragOperationGeneric;
}
Below code will print nil because you are not dragging anything on NSView.
SSDragDropView *dragView = [SSDragDropView new];
NSLog(#"DragView Value is %#",[dragView textToDisplay]);

Drag & drop (<NSDraggingDestination>) in Cocoa does not work

I want to implement some "simple" drag & drop into my Mac application.
I dragged in a view and entered "MyView" in my nib file accordingly.However I do not get any response in my console (I try to log messages whenever any of the protocol methods are triggered)
I have subclassed NSView like this:
#interface MyView : NSView <NSDraggingDestination>{
NSImageView* imageView;
}
and implement it like this:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self registerForDraggedTypes:[NSImage imagePasteboardTypes]];
NSRect rect = NSMakeRect(150, 0, 400, 300);
imageView = [[NSImageView alloc] initWithFrame:rect];
[imageView setImageScaling:NSScaleNone];
[imageView setImage:[NSImage imageNamed:#"test.png"]];
[self addSubview:imageView];
}
return self;
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
NSLog(#"entered");
return NSDragOperationCopy;
}
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender{
return NSDragOperationCopy;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender{
NSLog(#"exited");
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender{
NSLog(#"som");
return YES;
}
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
NSPasteboard *pboard = [sender draggingPasteboard];
if ( [[pboard types] containsObject:NSURLPboardType] ) {
NSURL *fileURL = [NSURL URLFromPasteboard:pboard];
NSLog(#"%#", fileURL);
}
return YES;
}
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender{
NSLog(#"conclude sth");
}
- (void)draggingEnded:(id <NSDraggingInfo>)sender{
NSLog(#"ended");
}
- (BOOL)wantsPeriodicDraggingUpdates{
NSLog(#"wants updates");
}
- (void)updateDraggingItemsForDrag:(id <NSDraggingInfo>)sender NS_AVAILABLE_MAC(10_7){
}
If anyone still needs this, using:
[self registerForDraggedTypes:[NSArray arrayWithObjects:
NSFilenamesPboardType, nil]];
instead of:
[self registerForDraggedTypes:
[NSImage imagePasteboardTypes]]; // BAD: dropped image runs away, no draggingdestination protocol methods sent...
solved this problem for me. I suspect this works because my XIB is targeting osX 10.5. NSFilenamesPboardType represents a 10.5-and-previous 'standard data' UTI and [NSImage imagePasteboardTypes] returns 10.6-and-after standard data UTIs.
By the way, in - (BOOL)performDragOperation:(id NSDraggingInfo)sender, you can get a path for the file that was dropped with:
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
Got the solution here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DragandDrop/Tasks/acceptingdrags.html#//apple_ref/doc/uid/20000993-BABHHIHC

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 do I stop a sound when a new sound button is pressed

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
}

Drag and Drop folder view cocoa

I need to make a drag and drop view in cocoa that will accept folders. I know it will use things like NSView and probably registerForDraggedTypes: (which I still am not sure how to go about using). Does anyone know how to get this working?
Thanks in advance
Make a class called DragDropView that subclasses NSView and set the view in MainMenu.xib to be of this type (Select your view, go to Identity Inspecor and write DragDropView in Custom Class).
Write the code (see below) for DragDropView and Run it. An empty window should appear.
Drag some folders onto your window. You should get the paths of the folders written in your console. Something like.
2014-02-01 11:18:10.435 Start[41767:303] (
"/Users/bob/Desktop/Heathers Animations",
"/Users/bob/Desktop/bird.atlas"
)
// DragDropView.h
#import <Cocoa/Cocoa.h>
#interface DragDropView : NSView
#end
// DragDropView.m
#import "DragDropView.h"
#implementation DragDropView {
BOOL isHighlighted;
}
- (void)awakeFromNib {
[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
}
- (BOOL)isHighlighted {
return isHighlighted;
}
- (void)setHighlighted:(BOOL)value {
isHighlighted = value;
[self setNeedsDisplay:YES];
}
- (void)drawRect:(NSRect)frame {
[super drawRect:frame];
if (isHighlighted) {
[NSBezierPath setDefaultLineWidth:6.0];
[[NSColor keyboardFocusIndicatorColor] set];
[NSBezierPath strokeRect:frame];
}
}
#pragma mark - Dragging
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
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<NSDraggingInfo>)sender {
NSArray *files = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
NSLog(#"%#", files);
}
#end
Most of what you need is in the drag and drop documentation, but what you need specifically is the NSFilenamesPboardType. It's an array if file paths.

Resources