Am getting an "Expected expression" error but can't figure out why on an IBAction method. Have commented out the error.
Can you tell me what's wrong? Thank you.
#import "RTViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface RTViewController () {
AVAudioPlayer *backgroundAudioPlayer;
SystemSoundID burnRubberSoundID;
BOOL touchInCar;
}
#end
#implementation RTViewController
#synthesize car;
#synthesize testDriveButton;
#synthesize backgroundImage;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Road Trip";
NSURL* backgroundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"CarRunning"
ofType:#"aif"]];
backgroundAudioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:backgroundURL error:nil];
backgroundAudioPlayer.numberOfLoops = -1;
[backgroundAudioPlayer prepareToPlay];
NSURL* burnRubberURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"BurnRubber" ofType:#"aif"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)burnRubberURL, &burnRubberSoundID);
[testDriveButton setBackgroundImage:[UIImage animatedImageNamed:#"Button" duration:1.0 ] forState:UIControlStateNormal];
}
- (void)viewDidUnload
{
[self setCar:nil];
[self setTestDriveButton:nil];
[self setBackgroundImage:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)TestDrive:(id)sender {
AudioServicesPlaySystemSound(burnRubberSoundID);
[self performSelector:#selector(playCarSound) withObject:self afterDelay:.2];
CGPoint center = CGPointMake(car.center.x, self.view.frame.origin.y + car.frame.size.height/2);
[UIView animateWithDuration:3 animations:^ {
car.center = center;
}
completion:^(BOOL finished) {
[self rotate];
}];
}
-(void)playCarSound {
[backgroundAudioPlayer play];
}
- (void)rotate {
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI);
void (^animation) () = ^() {
car.transform = transform;
};
void (^completion) (BOOL) = ^ (BOOL finished) {
[self returnCar];
};
[UIView animateWithDuration:3 animations:animation completion:completion];
}
- (void)returnCar {
CGPoint center = CGPointMake(car.center.x, self.view.frame.origin.y + self.view.frame.size.height - car.frame.size.height/2);
void (^animation)() = ^() {
car.center = center;
};
void (^completion)(BOOL) = ^(BOOL finished) {
[self continueRotation];
};
[UIView animateWithDuration:3 animations:animation completion:completion];
}
- (void)continueRotation {
CGAffineTransform transform = CGAffineTransformMakeRotation(0);
void (^animation)() = ^() {
car.transform = transform;
};
void (^completion)(BOOL) = ^(BOOL finished) {
[backgroundAudioPlayer stop];
[backgroundAudioPlayer prepareToPlay];
};
[UIView animateWithDuration:3 animations:animation completion:completion];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if(CGRectContainsPoint(car.frame, [touch locationInView:self.view]))
touchInCar=YES;
else {
touchInCar=NO;
[super touchesBegan:touches withEvent:event];
}
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(handleSwipeGesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeGesture];
- (IBAction)handleSwipeGesture:(id)sender { // Expected expression
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:#"Content"];
[[self navigationController]pushViewController:viewController animated:YES];
}
}
#end
The problem is that you never closed out the method
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
with its own curly brace. One visual cue is that the method
- (IBAction)handleSwipeGesture:(id)sender
(where your error is) starts out indented.
Related
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];
Edit: Here's my AppDelegate as well (part of it)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
GameViewController *gameViewController = [[GameViewController alloc]init];
NSLog(#"NSLOG %#", [[gameViewController view]class]);
_bannerViewController = [[BannerViewController alloc]initWithContentViewController:gameViewController];
self.window.rootViewController = _bannerViewController;
[self.window makeKeyAndVisible];
return YES;
}
I am about to give up. I have tried 5 different ways just these past few days to get literally one single iAd to show correctly and as simple as Apple makes it seem, literally 100% of the time I either see no ad or get an error. I have followed the Apple documentation EXACTLY.
The only clue I have is in these two lines
GameViewController *gameViewController = [[GameViewController alloc]init];
NSLog(#"NSLOG %#", [[gameViewController view]class]);
Which are in my app delegate. The NSLog gives me "UIView". No. Why? Why would that ever be a UIView, it should be an SKView, because GameViewController was pre-written for me by apple for sprite kit. How could that possibly give me the wrong object?
I am getting 'NSInvalidArgumentException', reason: '-[UIView scene]: unrecognized selector sent to instance 0x174191780' which others have recommended to fix by putting the originalContent statement but I already have that and it isn't working.
Banner view controller:
#import "BannerViewController.h"
NSString * const BannerViewActionWillBegin = #"BannerViewActionWillBegin";
NSString * const BannerViewActionDidFinish = #"BannerViewActionDidFinish";
#interface BannerViewController () <ADBannerViewDelegate>
#end
#implementation BannerViewController {
ADBannerView *_bannerView;
UIViewController *_contentController;
}
-(instancetype)initWithContentViewController:(UIViewController *)contentController{
NSAssert(contentController != nil, #"Attempting to initialize a BannerViewController with a nil contentController.");
self = [super init];
if (self != nil) {
_bannerView = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];
_contentController = contentController;
_bannerView.delegate = self;
}
return self;
}
-(void)loadView{
UIView *contentView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
//Have also tried SKView *contentView = [[SKView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
[contentView addSubview:_bannerView];
[self addChildViewController:_contentController];
[contentView addSubview:_contentController.view];
[_contentController didMoveToParentViewController:self];
self.view = contentView;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return [_contentController preferredInterfaceOrientationForPresentation];
}
-(NSUInteger)supportedInterfaceOrientations{
return [_contentController supportedInterfaceOrientations];
}
-(void)viewDidLayoutSubviews{
CGRect contentFrame = self.view.bounds, bannerFrame = CGRectZero;
bannerFrame.size = [_bannerView sizeThatFits:contentFrame.size];
if(_bannerView.bannerLoaded){
contentFrame.size.height -= bannerFrame.size.height;
bannerFrame.origin.y = contentFrame.size.height;
}else{
bannerFrame.origin.y = contentFrame.size.height;
}
_contentController.view.frame = contentFrame;
_bannerView.frame = bannerFrame;
}
-(void)bannerViewDidLoadAd:(ADBannerView *)banner{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave{
[[NSNotificationCenter defaultCenter]postNotificationName:BannerViewActionWillBegin object:self];
return YES;
}
-(void)bannerViewActionDidFinish:(ADBannerView *)banner{
[[NSNotificationCenter defaultCenter]postNotificationName:BannerViewActionDidFinish object:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Game View controller:
#interface GameViewController ()
#property (nonatomic, strong) IBOutlet UIView *contentView;
#end
#implementation GameViewController {
}
-(instancetype)init{
self = [super init];
if (self) {
}
return self;
}
-(void)viewDidLoad{
//self.canDisplayBannerAds = YES;
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
}
-(void)viewDidLayoutSubviews{
}
-(void)viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
SKView *skView = (SKView*)self.originalContentView;
if (!skView.scene) {
SKScene *scene = [GameScene sceneWithSize:skView.bounds.size];
[skView presentScene:scene];
//skView.showsPhysics = YES;
}
}
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return UIInterfaceOrientationMaskPortrait;
} else {
return UIInterfaceOrientationMaskAll;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
I figured it out. The answer, as I thought it would be, was incredibly simple and quite mind-boggling that Apple wouldn't put some sort of warning in their documentation, but then again maybe I am just too much of a noob and we are expected to know these kinds of things.
The answer, is that init was never being called in GameViewController, instead, initWithCoder: was being called. Once I NSLogged the init method and saw it wasn't being called, I figured this out.
I'm working on a project where images are spawned and you basically touch them and they are removed. How would I removed the object that I touched? I've thought of making a mutablearray to hold all the objects but i can't seem to figure anything out.
GameViewController.m
#import "GameViewController.h"
#import "Cig.h"
#interface GameViewController ()
#end
#implementation GameViewController
#synthesize scoreLbl, timeLbl;
//CLASS ONLY VARS
BOOL isGameOver;
int timeInt;
int scoreInt;
int cigsOnScreen;
NSMutableArray *spawnedCigs;
//CLASS ONLY VARS
//TIMER
-(void)count {
timeInt--;
timeLbl.text = [NSString stringWithFormat:#"Time: %i", timeInt];
if(timeInt == 0){
isGameOver = YES;
NSLog(#"Your Score For This Round: %i", scoreInt);
}
if(isGameOver == NO){
[self performSelector:#selector(count) withObject:nil afterDelay:1];
}
}
//TIMER
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)spawnCigs {
for(int i =0 ; i < 5; i++){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(arc4random()%760, arc4random()%430, 100, 23)];
UIImage *image = [UIImage imageNamed:#"Cig.png"];
[imageView setImage:image];
Cig *cig = [[Cig alloc] init];
[cig setTag:arc4random()%666];
[cig setImage:imageView];
[spawnedCigs addObject:cig];
[self.view addSubview:imageView];
}
[self performSelector:#selector(spawnCigs) withObject:nil afterDelay:5];
}
-(void)reset {
scoreLbl.text = #"Score:";
timeLbl.text = #"Time:";
isGameOver = NO;
timeInt = 60;
scoreInt = 0;
cigsOnScreen = 0;
spawnedCigs = [NSMutableArray arrayWithObjects:nil, nil];
[self performSelector:#selector(count) withObject:nil afterDelay:1];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self reset];
[self spawnCigs];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Code is pretty messy so please don't judge me on that.
Thanks for any help that is provided
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[[event allTouches]anyObject];
CGPoint touchPoint = [touch locationInView:touch.view];;
for (UIView *view in [self.view subviews])
{
if([view isMemberOfClass:[UIImageView class]])
{
if (CGRectContainsPoint(view.frame,touchPoint))
{
[view removeFromSuperview];
}
}
}
}
this helps you
use
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UIImageView *view in [self.view subviews])
{
if (view.tag==1)
{
[view removeFromSuperview];
}
if (view.tag==2)
{
[view removeFromSuperview];
}
}
}
try this your issue will be resolved. Don't forget to pass tab to your imageviews...
By using
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
method you will get the image view of selected image. simply remove the object from superview.
Have this implementation file which compiles and runs fine, but gives me an unused variable warning in a block. Am new to blocks, so am not quite sure what is wrong. Have commented the line where the warning is.
Can someone please explain this? Thanks in advance!
#import "RTViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface RTViewController () {
AVAudioPlayer *backgroundAudioPlayer;
SystemSoundID burnRubberSoundID;
}
#end
#implementation RTViewController
#synthesize car;
#synthesize testDriveButton;
#synthesize backgroundImage;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Road Trip";
NSURL* backgroundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"CarRunning"
ofType:#"aif"]];
backgroundAudioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:backgroundURL error:nil];
backgroundAudioPlayer.numberOfLoops = -1;
[backgroundAudioPlayer prepareToPlay];
NSURL* burnRubberURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"BurnRubber" ofType:#"aif"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)burnRubberURL, &burnRubberSoundID);
}
- (void)viewDidUnload
{
[self setCar:nil];
[self setTestDriveButton:nil];
[self setBackgroundImage:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)TestDrive:(id)sender {
AudioServicesPlaySystemSound(burnRubberSoundID);
[self performSelector:#selector(playCarSound) withObject:self afterDelay:.2];
CGPoint center = CGPointMake(car.center.x, self.view.frame.origin.y + car.frame.size.height/2);
[UIView animateWithDuration:3 animations:^ {
car.center = center;
}
completion:^(BOOL finished) {
[self rotate];
}];
}
-(void)playCarSound {
[backgroundAudioPlayer play];
}
- (void)rotate {
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI);
void (^animation) () = ^() {
car.transform = transform;
};
void (^completion) (BOOL) = ^ (BOOL finished) {
[self returnCar];
};
[UIView animateWithDuration:3 animations:animation completion:completion];
}
- (void)returnCar {
CGPoint center = CGPointMake(car.center.x, self.view.frame.origin.y + self.view.frame.size.height - car.frame.size.height/2);
void (^animation)() = ^() {
car.center = center;
};
void (^completion)(BOOL) = ^(BOOL finished) {
[self continueRotation];
};
[UIView animateWithDuration:3 animations:animation completion:completion];
}
- (void)continueRotation {
CGAffineTransform transform = CGAffineTransformMakeRotation(0);
void (^animation)() = ^() {
car.transform = transform;
};
void (^completion)(BOOL) = ^(BOOL finished) { //Unused variable 'completion'
[backgroundAudioPlayer stop];
[backgroundAudioPlayer prepareToPlay];
};
[UIView animateWithDuration:3 animations:animation completion:nil];
}
#end
The problem is that you forgot to use the variable completion in the line:
[UIView animateWithDuration:3 animations:animation completion:nil];
^^^
Here
So change that line to this:
[UIView animateWithDuration:3 animations:animation completion:completion];
Also, note that you can write your code like this:
- (void)continueRotation
{
[UIView animateWithDuration:3 animations:^{
car.transform = CGAffineTransformMakeRotation(0);
} completion:^(BOOL finished) {
[backgroundAudioPlayer stop];
[backgroundAudioPlayer prepareToPlay];
}];
}
That warning simply means that you've instantiated a variable but are not using it anywhere in the code.
But it's a warning, your code will still compile and should work fine. It's just telling you there's no reason to instantiate something if it's never gonna be used.
I'm trying to re-write an application I have for Windows in Objective-C for my Mac, and I want to be able to do something like Mac's hot corners. If I move my mouse to the left side of the screen it will make a window visible, if I move it outside of the window location the window will hide again. (window would be pushed up to the left side of screen).
Does anyone know where I can find some demo code (or reference) on how to do this, or at least how to tell where the mouse is at, even if the current application is not on top. (not sure how to word this, too used to Windows world).
Thank you
-Brad
You're going to want to implement an invisible window on the edge of the screen with the window order set so it's always on top. Then, you can listen for mouse-moved events in this window.
To set the window to be invisible and on top, make a window subclass use calls like:
[self setBackgroundColor:[NSColor clearColor]];
[self setExcludedFromWindowsMenu:YES];
[self setCanHide:NO];
[self setLevel:NSScreenSaverWindowLevel];
[self setAlphaValue:0.0f];
[self setOpaque:NO];
[self orderFrontRegardless];
then, to turn on mouse moved events,
[self setAcceptsMouseMovedEvents:YES];
will cause the window to get calls to:
- (void)mouseMoved:(NSEvent *)theEvent
{
NSLog(#"mouse moved into invisible window.");
}
So hopefully that's enough to give you a start.
-Ken
Here's AutoHidingWindow - a subclass of SlidingWindow which pops up when the mouse hits the edge of the screen. Feedback welcome.
#interface ActivationWindow : NSWindow
{
AutoHidingWindow *_activationDelegate;
NSTrackingArea *_trackingArea;
}
- (ActivationWindow*)initWithDelegate:(AutoHidingWindow*)activationDelegate;
#property (assign) AutoHidingWindow *activationDelegate;
#property (retain) NSTrackingArea *trackingArea;
- (void)adjustWindowFrame;
- (void)adjustTrackingArea;
#end
#interface AutoHidingWindow ()
- (void)autoShow;
- (void)autoHide;
#end
#implementation AutoHidingWindow
- (id)initWithContentRect:(NSRect) contentRect
styleMask:(unsigned int) styleMask
backing:(NSBackingStoreType) backingType
defer:(BOOL) flag
{
if ((self = [super initWithContentRect:contentRect
styleMask:NSBorderlessWindowMask
backing:backingType
defer:flag])) {
_activationWindow = [[ActivationWindow alloc] initWithDelegate:self];
}
return self;
}
#synthesize activationWindow = _activationWindow;
- (void)dealloc
{
[_activationWindow release], _activationWindow = nil;
[super dealloc];
}
- (void)makeKeyAndOrderFront:(id)sender
{
[super makeKeyAndOrderFront:sender];
}
- (void)autoShow
{
[self makeKeyAndOrderFront:self];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(autoHide) object:nil];
[self performSelector:#selector(autoHide) withObject:nil afterDelay:2];
}
- (void)autoHide
{
NSPoint mouseLocation = [NSEvent mouseLocation];
NSRect windowFrame = [self frame];
if (NSPointInRect(mouseLocation, windowFrame)) {
[self performSelector:#selector(autoHide) withObject:nil afterDelay:2];
}
else {
[self orderOut:self];
}
}
#end
#implementation ActivationWindow
- (ActivationWindow*)initWithDelegate:(AutoHidingWindow*)activationDelegate
{
if ((self = [super initWithContentRect:[[NSScreen mainScreen] frame]
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO]) != nil) {
_activationDelegate = activationDelegate;
[self setBackgroundColor:[NSColor clearColor]];
[self setExcludedFromWindowsMenu:YES];
[self setCanHide:NO];
[self setHasShadow:NO];
[self setLevel:NSScreenSaverWindowLevel];
[self setAlphaValue:0.0];
[self setIgnoresMouseEvents:YES];
[self setOpaque:NO];
[self orderFrontRegardless];
[self adjustWindowFrame];
[self.activationDelegate addObserver:self
forKeyPath:#"slidingEdge"
options:0
context:#"slidingEdge"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(screenParametersChanged:)
name:NSApplicationDidChangeScreenParametersNotification
object:nil];
}
return self;
}
#synthesize activationDelegate = _activationDelegate;
#synthesize trackingArea = _trackingArea;
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([#"slidingEdge" isEqual:context]) {
[self adjustTrackingArea];
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self.activationDelegate removeObserver:self forKeyPath:#"slidingEdge"];
_activationDelegate = nil;
[_trackingArea release], _trackingArea = nil;
[super dealloc];
}
- (void)screenParametersChanged:(NSNotification *)notification
{
[self adjustWindowFrame];
}
- (void)adjustWindowFrame
{
NSScreen *mainScreen = [NSScreen mainScreen];
CGFloat menuBarHeight = [NSMenuView menuBarHeight];
NSRect windowFrame = [mainScreen frame];
windowFrame.size.height -= menuBarHeight;
[self setFrame:windowFrame display:NO];
[self adjustTrackingArea];
}
- (void)adjustTrackingArea
{
NSView *contentView = [self contentView];
NSRect trackingRect = contentView.bounds;
CGRectEdge slidingEdge = self.activationDelegate.slidingEdge;
CGFloat trackingRectSize = 2.0;
switch (slidingEdge) {
case CGRectMaxXEdge:
trackingRect.origin.x = trackingRect.origin.x + trackingRect.size.width - trackingRectSize;
trackingRect.size.width = trackingRectSize;
break;
case CGRectMaxYEdge:
trackingRect.origin.y = trackingRect.origin.y + trackingRect.size.height - trackingRectSize;
trackingRect.size.height = trackingRectSize;
break;
case CGRectMinXEdge:
trackingRect.origin.x = 0;
trackingRect.size.width = trackingRectSize;
break;
case CGRectMinYEdge:
default:
trackingRect.origin.y = 0;
trackingRect.size.height = trackingRectSize;
}
NSTrackingAreaOptions options =
NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
NSTrackingActiveAlways |
NSTrackingEnabledDuringMouseDrag;
NSTrackingArea *trackingArea = self.trackingArea;
if (trackingArea != nil) {
[contentView removeTrackingArea:trackingArea];
}
trackingArea = [[NSTrackingArea alloc] initWithRect:trackingRect
options:options
owner:self
userInfo:nil];
[contentView addTrackingArea:trackingArea];
self.trackingArea = [trackingArea autorelease];
}
- (void)mouseEntered:(NSEvent *)theEvent
{
[self.activationDelegate autoShow];
}
- (void)mouseMoved:(NSEvent *)theEvent
{
[self.activationDelegate autoShow];
}
- (void)mouseExited:(NSEvent *)theEvent
{
}
#end
you may look how we did it in the Visor project:
http://github.com/binaryage/visor/blob/master/src/Visor.m#L1025-1063
Here's what I came up with. Thanks to Peter for the above tips.
#interface SlidingWindow : NSWindow
{
CGRectEdge _slidingEdge;
NSView *_wrapperView;
}
#property (nonatomic, assign) CGRectEdge slidingEdge;
#property (nonatomic, retain) NSView *wrapperView;
-(id)initWithContentRect:(NSRect) contentRect
styleMask:(unsigned int) styleMask
backing:(NSBackingStoreType) backingType
defer:(BOOL) flag;
- (NSView*)wrapperViewWithFrame:(NSRect)bounds;
- (BOOL)mayOrderOut;
#end
#interface SlidingWindow ()
- (void)adjustWrapperView;
- (void)setWindowWidth:(NSNumber*)width;
- (void)setWindowHeight:(NSNumber*)height;
#end
#implementation SlidingWindow
#synthesize slidingEdge = _slidingEdge;
#synthesize wrapperView = _wrapperView;
- (id)initWithContentRect:(NSRect) contentRect
styleMask:(unsigned int) styleMask
backing:(NSBackingStoreType) backingType
defer:(BOOL) flag
{
if ((self = [super initWithContentRect:contentRect
styleMask:NSBorderlessWindowMask
backing:backingType
defer:flag])) {
/* May want to setup some other options,
like transparent background or something */
[self setSlidingEdge:CGRectMaxYEdge];
[self setHidesOnDeactivate:YES];
[self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
}
return self;
}
- (NSView*)wrapperViewWithFrame:(NSRect)bounds
{
return [[[NSView alloc] initWithFrame:bounds] autorelease];
}
- (void)adjustWrapperView
{
if (self.wrapperView == nil) {
NSRect frame = [self frame];
NSRect bounds = NSMakeRect(0, 0, frame.size.width, frame.size.height);
NSView *wrapperView = [self wrapperViewWithFrame:bounds];
NSArray *subviews = [[[[self contentView] subviews] copy] autorelease];
for (NSView *view in subviews) {
[wrapperView addSubview:view];
}
[wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[[self contentView] addSubview:wrapperView];
self.wrapperView = wrapperView;
}
switch (self.slidingEdge) {
case CGRectMaxXEdge:
[self.wrapperView setAutoresizingMask:(NSViewHeightSizable | NSViewMaxXMargin)];
break;
case CGRectMaxYEdge:
[self.wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewMaxYMargin)];
break;
case CGRectMinXEdge:
[self.wrapperView setAutoresizingMask:(NSViewHeightSizable | NSViewMinXMargin)];
break;
case CGRectMinYEdge:
default:
[self.wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
}
}
- (void)makeKeyAndOrderFront:(id)sender
{
[self adjustWrapperView];
if ([self isVisible]) {
[super makeKeyAndOrderFront:sender];
}
else {
NSRect screenRect = [[NSScreen menubarScreen] visibleFrame];
NSRect windowRect = [self frame];
CGFloat x;
CGFloat y;
NSRect startWindowRect;
NSRect endWindowRect;
switch (self.slidingEdge) {
case CGRectMinXEdge:
x = 0;
y = (screenRect.size.height - windowRect.size.height) / 2 + screenRect.origin.y;
startWindowRect = NSMakeRect(x - windowRect.size.width, y, 0, windowRect.size.height);
break;
case CGRectMinYEdge:
x = (screenRect.size.width - windowRect.size.width) / 2 + screenRect.origin.x;
y = 0;
startWindowRect = NSMakeRect(x, y - windowRect.size.height, windowRect.size.width, 0);
break;
case CGRectMaxXEdge:
x = screenRect.size.width - windowRect.size.width + screenRect.origin.x;
y = (screenRect.size.height - windowRect.size.height) / 2 + screenRect.origin.y;
startWindowRect = NSMakeRect(x + windowRect.size.width, y, 0, windowRect.size.height);
break;
case CGRectMaxYEdge:
default:
x = (screenRect.size.width - windowRect.size.width) / 2 + screenRect.origin.x;
y = screenRect.size.height - windowRect.size.height + screenRect.origin.y;
startWindowRect = NSMakeRect(x, y + windowRect.size.height, windowRect.size.width, 0);
}
endWindowRect = NSMakeRect(x, y, windowRect.size.width, windowRect.size.height);
[self setFrame:startWindowRect display:NO animate:NO];
[super makeKeyAndOrderFront:sender];
[self setFrame:endWindowRect display:YES animate:YES];
[self performSelector:#selector(makeResizable)
withObject:nil
afterDelay:1];
}
}
- (void)makeResizable
{
NSView *wrapperView = self.wrapperView;
NSRect frame = [self frame];
NSRect bounds = NSMakeRect(0, 0, frame.size.width, frame.size.height);
[wrapperView setFrame:bounds];
[wrapperView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
}
- (void)orderOut:(id)sender
{
[self adjustWrapperView];
NSRect startWindowRect = [self frame];
NSRect endWindowRect;
switch (self.slidingEdge) {
case CGRectMinXEdge:
endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
0,
startWindowRect.size.height);
break;
case CGRectMinYEdge:
endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
startWindowRect.size.width,
0);
break;
case CGRectMaxXEdge:
endWindowRect = NSMakeRect(startWindowRect.origin.x + startWindowRect.size.width,
startWindowRect.origin.y,
0,
startWindowRect.size.height);
break;
case CGRectMaxYEdge:
default:
endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y + startWindowRect.size.height,
startWindowRect.size.width,
0);
}
[self setFrame:endWindowRect display:YES animate:YES];
switch (self.slidingEdge) {
case CGRectMaxXEdge:
case CGRectMinXEdge:
if (startWindowRect.size.width > 0) {
[self performSelector:#selector(setWindowWidth:)
withObject:[NSNumber numberWithDouble:startWindowRect.size.width]
afterDelay:0];
}
break;
case CGRectMaxYEdge:
case CGRectMinYEdge:
default:
if (startWindowRect.size.height > 0) {
[self performSelector:#selector(setWindowHeight:)
withObject:[NSNumber numberWithDouble:startWindowRect.size.height]
afterDelay:0];
}
}
[super orderOut:sender];
}
- (void)setWindowWidth:(NSNumber*)width
{
NSRect startWindowRect = [self frame];
NSRect endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
[width doubleValue],
startWindowRect.size.height);
[self setFrame:endWindowRect display:NO animate:NO];
}
- (void)setWindowHeight:(NSNumber*)height
{
NSRect startWindowRect = [self frame];
NSRect endWindowRect = NSMakeRect(startWindowRect.origin.x,
startWindowRect.origin.y,
startWindowRect.size.width,
[height doubleValue]);
[self setFrame:endWindowRect display:NO animate:NO];
}
- (void)resignKeyWindow
{
[self orderOut:self];
[super resignKeyWindow];
}
- (BOOL)canBecomeKeyWindow
{
return YES;
}
- (void)performClose:(id)sender
{
[self close];
}
- (void)dealloc
{
[_wrapperView release], _wrapperView = nil;
[super dealloc];
}
#end
#implementation NSScreen (MenubarScreen)
+ (NSScreen*)menubarScreen
{
NSArray *screens = [self screens];
if ([screens count] > 0) {
return [screens objectAtIndex:0];
}
return nil;
}
#end