Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preview View not Auto-Rotating #59

Closed
sportsy opened this issue Aug 29, 2014 · 5 comments
Closed

Preview View not Auto-Rotating #59

sportsy opened this issue Aug 29, 2014 · 5 comments

Comments

@sportsy
Copy link

sportsy commented Aug 29, 2014

img_4827

Attached is an image of what's happening.

When I rotate the phone, the rest of the views in the XIB rotate and scale properly, but the preview layer basically stays the same. When recording, the video does come out properly, it's just the preview layer.

#import "RecordChallengeViewController.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "SCAudioTools.h"
#import "SCRecorderFocusView.h"
#import "SCRecorder.h"
#import "SCRecordSessionManager.h"
#import "SCTouchDetector.h"
#import "SCAssetExportSession.h"

#import "GridView.h"
#import "SBJson.h"

#define kVideoPreset AVCaptureSessionPresetHigh

@interface RecordChallengeViewController () {
    SCRecorder *_recorder;
    UIImage *_photo;
    SCRecordSession *_recordSession;
}

@property (strong, nonatomic) SCRecorderFocusView *focusView;

@end

@implementation RecordChallengeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];


    _secondDelay = 0;

    aws = [[SportsyAWS alloc] init];
    model = [SportsyModel sharedModel];
    analytics = [SportsyAnalytics sharedModel];

    _recorder = [SCRecorder recorder];
    _recorder.sessionPreset = kVideoPreset;
    _recorder.audioEnabled = YES;
    _recorder.delegate = self;
    _recorder.autoSetVideoOrientation = YES;


    UIView *previewView = self.previewView;
    previewView.backgroundColor = [UIColor redColor];
    _recorder.previewView = previewView;

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeOpenSlides:)];
    tapRecognizer.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tapRecognizer];

    [self.retakeButton addTarget:self action:@selector(handleRetakeButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.reverseCamera addTarget:self action:@selector(handleReverseCameraTapped:) forControlEvents:UIControlEventTouchUpInside];

    self.focusView = [[SCRecorderFocusView alloc] initWithFrame:previewView.bounds];
    self.focusView.recorder = _recorder;
    [previewView addSubview:self.focusView];

    self.focusView.outsideFocusTargetImage = [UIImage imageNamed:@"record-focus"];
    self.focusView.insideFocusTargetImage = [UIImage imageNamed:@"record-focus"];

    [_recorder openSession:^(NSError *sessionError, NSError *audioError, NSError *videoError, NSError *photoError) {
        NSLog(@"==== Opened session ====");
        NSLog(@"Session error: %@", sessionError.description);
        NSLog(@"Audio error : %@", audioError.description);
        NSLog(@"Video error: %@", videoError.description);
        NSLog(@"Photo error: %@", photoError.description);
        NSLog(@"=======================");
        [self prepareCamera];
    }];

    GridView *gView = [[GridView alloc] initWithFrame:self.view.frame];
    gView.backgroundColor = [UIColor clearColor];
    [self.gridContainerView addSubview:gView];

    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [_recorder startRunningSession];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [_recorder endRunningSession];
}

- (void) prepareCamera {
    if (_recorder.recordSession == nil) {

        SCRecordSession *session = [SCRecordSession recordSession];
        //session.suggestedMaxRecordDuration = CMTimeMakeWithSeconds(5, 10000);

        _recorder.recordSession = session;
    }
}

- (void)showError:(NSError*)error {
    [[[UIAlertView alloc] initWithTitle:@"Something went wrong" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}



- (void)recorder:(SCRecorder *)recorder didCompleteRecordSession:(SCRecordSession *)recordSession {

    [self finishSession:recordSession];

}

- (void)recorder:(SCRecorder *)recorder didInitializeAudioInRecordSession:(SCRecordSession *)recordSession error:(NSError *)error {
    if (error == nil) {
        NSLog(@"Initialized audio in record session");
    } else {
        NSLog(@"Failed to initialize audio in record session: %@", error.localizedDescription);
    }
}

- (void)recorder:(SCRecorder *)recorder didInitializeVideoInRecordSession:(SCRecordSession *)recordSession error:(NSError *)error {
    if (error == nil) {
        NSLog(@"Initialized video in record session");
    } else {
        NSLog(@"Failed to initialize video in record session: %@", error.localizedDescription);
    }
}

- (void)recorder:(SCRecorder *)recorder didBeginRecordSegment:(SCRecordSession *)recordSession error:(NSError *)error {
    NSLog(@"Began record segment: %@", error);
}

- (void)recorder:(SCRecorder *)recorder didEndRecordSegment:(SCRecordSession *)recordSession segmentIndex:(NSInteger)segmentIndex error:(NSError *)error {
    DLog(@"Ended record segment: %@", error);
}

#pragma mark - Focus
- (void)recorderDidStartFocus:(SCRecorder *)recorder {
    [self.focusView showFocusAnimation];
}

- (void)recorderDidEndFocus:(SCRecorder *)recorder {
    [self.focusView hideFocusAnimation];
}

- (void)recorderWillStartFocus:(SCRecorder *)recorder {
    [self.focusView showFocusAnimation];
}

#pragma mark - Recorder Actions
- (void) handleStopButtonTapped:(id)sender {
    SCRecordSession *recordSession = _recorder.recordSession;

    if (recordSession != nil) {
        [self finishSession:recordSession];
    }
}

- (void)finishSession:(SCRecordSession *)recordSession {
    [recordSession endRecordSegment:^(NSInteger segmentIndex, NSError *error) {
        [[SCRecordSessionManager sharedInstance] saveRecordSession:recordSession];

        _recordSession = recordSession;
        [self prepareCamera];
    }];
}


-(IBAction)delayClick:(id)sender {

    CGPoint currentPositionDescription = self.descriptionScrollView.contentOffset;

    if(currentPositionDescription.y >= self.descriptionView.frame.origin.y) {
        [_descriptionBtn setImage:[UIImage imageNamed:@"record-notes"] forState:UIControlStateNormal];
        [self.descriptionScrollView setContentOffset:CGPointMake(self.descriptionView.frame.origin.x, currentPositionDescription.y - self.descriptionView.frame.origin.y) animated:YES];
    }

    CGPoint currentPosition = self.delayScrollView.contentOffset;

    if(currentPosition.y >= self.delayView.frame.origin.y) {
        [_delayBtn setImage:[UIImage imageNamed:@"record-delay"] forState:UIControlStateNormal];
        [self.delayScrollView setContentOffset:CGPointMake(self.delayView.frame.origin.x, currentPosition.y - self.delayView.frame.origin.y) animated:YES];
    } else {
        [_delayBtn setImage:[UIImage imageNamed:@"record-delay-on"] forState:UIControlStateNormal];
        [self.delayScrollView setContentOffset:CGPointMake(self.delayView.frame.origin.x, self.delayView.frame.origin.y) animated:YES];
    }

    if(_secondDelay > 0) {
        [_delayBtn setImage:[UIImage imageNamed:@"record-delay-on"] forState:UIControlStateNormal];
        _secondLabel.text = [NSString stringWithFormat:@"%i secs", _secondDelay];
    } else {
        _secondLabel.text = @"";
    }

}
-(IBAction)micClick:(id)sender {
    if(_recorder.audioEnabled) {
        [_micBtn setImage:[UIImage imageNamed:@"record-mic"] forState:UIControlStateNormal];
        _recorder.audioEnabled = NO;
    } else {
        [_micBtn setImage:[UIImage imageNamed:@"record-mic-on"] forState:UIControlStateNormal];
        _recorder.audioEnabled = YES;
    }
    [self prepareCamera];
}
-(IBAction)gridClick:(id)sender {
    if(self.gridContainerView.hidden) {
        [_gridBtn setImage:[UIImage imageNamed:@"record-grid-on"] forState:UIControlStateNormal];
        self.gridContainerView.hidden = NO;
    } else {
        [_gridBtn setImage:[UIImage imageNamed:@"record-grid"] forState:UIControlStateNormal];
        self.gridContainerView.hidden = YES;
    }
}
-(IBAction)descriptionClick:(id)sender {

    CGPoint currentPositionDelay = self.delayScrollView.contentOffset;

    if(currentPositionDelay.y >= self.delayView.frame.origin.y) {
        [_delayBtn setImage:[UIImage imageNamed:@"record-delay"] forState:UIControlStateNormal];
        [self.delayScrollView setContentOffset:CGPointMake(self.delayView.frame.origin.x, currentPositionDelay.y - self.delayView.frame.origin.y) animated:YES];
    }

    CGPoint currentPosition = self.descriptionScrollView.contentOffset;

    if(currentPosition.y >= self.descriptionView.frame.origin.y) {
        [_descriptionBtn setImage:[UIImage imageNamed:@"record-notes"] forState:UIControlStateNormal];
        [self.descriptionScrollView setContentOffset:CGPointMake(self.descriptionView.frame.origin.x, currentPosition.y - self.descriptionView.frame.origin.y) animated:YES];
    } else {
        [_descriptionBtn setImage:[UIImage imageNamed:@"record-notes-on"] forState:UIControlStateNormal];
        [self.descriptionScrollView setContentOffset:CGPointMake(self.descriptionView.frame.origin.x, self.descriptionView.frame.origin.y) animated:YES];
    }

}

-(IBAction)delayItemClick:(id)sender {
    UIButton *instanceButton = (UIButton *)sender;
    int tag = instanceButton.tag;
    _secondDelay = tag;
    if(_secondDelay > 0) {
        [_delayBtn setImage:[UIImage imageNamed:@"record-delay-on"] forState:UIControlStateNormal];
        _secondLabel.text = [NSString stringWithFormat:@"%i secs", _secondDelay];
    } else {
        _secondLabel.text = @"";
    }

    //Disable all selected buttons
    [_fifteenSecondBtn setSelected:NO];
    [_tenSecondBtn setSelected:NO];
    [_fiveSecondBtn setSelected:NO];
    [_noDelayBtn setSelected:NO];

    [instanceButton setSelected:YES];

}

- (void) handleRetakeButtonTapped:(id)sender {
    SCRecordSession *recordSession = _recorder.recordSession;

    if (recordSession != nil) {
        _recorder.recordSession = nil;

        // If the recordSession was saved, we don't want to completely destroy it
        if ([[SCRecordSessionManager sharedInstance] isSaved:recordSession]) {
            [recordSession endRecordSegment:nil];
        } else {
            [recordSession cancelSession:nil];
        }
    }

    [self prepareCamera];
}

- (void) handleReverseCameraTapped:(id)sender {
    [_recorder switchCaptureDevices];
}

-(IBAction)recordPauseClick:(id)sender {
    if([_recorder isRecording]) {
        [_recordBtn setImage:[UIImage imageNamed:@"record-btn"] forState:UIControlStateNormal];
        DLog(@"TRYING TO END SESSION");
        SCRecordSession *recordSession = _recorder.recordSession;
        _recorder.recordSession = nil;

        [recordSession endSession:^(NSError *error) {
            DLog(@"END SESSION CALL");
            if (error == nil) {
                NSURL *fileUrl = recordSession.outputUrl;
                NSString *videoFileName = [NSString stringWithFormat:@"%@-%@.mp4", [model uid], [model getMongoIdFromDictionary:_challengeDict]];
                [aws uploadWithBackgroundThread:fileUrl withFileName:videoFileName];
                [self dismissViewControllerAnimated:YES completion:nil];

            } else {
                DLog(@"%@", error);
            }
        }];

    } else {
        if(_secondDelay > 0) {
            _delayTimerLabel.text = [NSString stringWithFormat:@"%i", _secondDelay];
            _delayTimerView.hidden = NO;
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        } else {
            [_recorder record];
        }

        [_recordBtn setImage:[UIImage imageNamed:@"record-btn-stop"] forState:UIControlStateNormal];
    }



}

-(void)timerFired {
    if(_secondDelay > 0){
        _secondDelay-=1;
        if(_secondDelay>-1) {
            _delayTimerLabel.text = [NSString stringWithFormat:@"%i", _secondDelay];
        }
    } else {
        _delayTimerView.hidden = YES;
        [_recorder record];
        [_timer invalidate];
    }
}

-(void)closeOpenSlides:(UITapGestureRecognizer *)recognizer {
    CGPoint currentPositionDelay = self.delayScrollView.contentOffset;

    if(currentPositionDelay.y >= self.delayView.frame.origin.y) {
        [_delayBtn setImage:[UIImage imageNamed:@"record-delay"] forState:UIControlStateNormal];
        [self.delayScrollView setContentOffset:CGPointMake(self.delayView.frame.origin.x, currentPositionDelay.y - self.delayView.frame.origin.y) animated:YES];
    }

    CGPoint currentPositionDescription = self.descriptionScrollView.contentOffset;

    if(currentPositionDescription.y >= self.descriptionView.frame.origin.y) {
        [_descriptionBtn setImage:[UIImage imageNamed:@"record-notes"] forState:UIControlStateNormal];
        [self.descriptionScrollView setContentOffset:CGPointMake(self.descriptionView.frame.origin.x, currentPositionDescription.y - self.descriptionView.frame.origin.y) animated:YES];
    }

}


/*
- (void)handleTouchDetected:(SCTouchDetector*)touchDetector {
    if (touchDetector.state == UIGestureRecognizerStateBegan) {
        [_recorder record];
    } else if (touchDetector.state == UIGestureRecognizerStateEnded) {
        [_recorder pause];
    }
}
*/

- (void) didRotate:(NSNotification *)notification
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

    if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight)
    {
        _recorder.previewView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width);
    } else {
        _recorder.previewView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
    }
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    //[self prepareCamera];
}

- (BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers {
    return YES;
}

- (BOOL)shouldAutomaticallyForwardRotationMethods {
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
@rFlex
Copy link
Owner

rFlex commented Aug 30, 2014

You shouldn't need to register for the orientation notification. Just override "viewDidLayoutSubviews" and call [SCRecorder previewViewFrameChanged]

@sportsy
Copy link
Author

sportsy commented Sep 1, 2014

Perfect. Thank you.

Would be helpful to a little wiki!

@sportsy sportsy closed this as completed Sep 1, 2014
@sportsy
Copy link
Author

sportsy commented Oct 2, 2014

This is now happening again on iOS 8. Any suggestions on fixing this?

@sportsy sportsy reopened this Oct 2, 2014
@sportsy
Copy link
Author

sportsy commented Oct 2, 2014

After a little hacking around, i was able to get it working again

@sportsy sportsy closed this as completed Oct 2, 2014
@Ankish
Copy link

Ankish commented Jun 10, 2015

How did you fix this ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants