QuickBlox / quickblox-ios-sdk

QuickBlox iOS SDK for messaging and video calling
https://quickblox.com/developers/IOS
MIT License
397 stars 358 forks source link

setVideoTrack works with caller but not receiver #915

Closed jlubeck closed 6 years ago

jlubeck commented 6 years ago

New Issue Checklist

I'm using the latest SDK. I can't make the RemoteVideoView work on the receiving end. Whenever I make a video call, the caller gets the video from the receiver. But not the other way around. If I switch roles, same issue again.

Here are my logs on the caller: https://pastebin.com/zx7Qedse Here are my logs on the receiver: https://pastebin.com/zhcCJ6Sn

Here is the code on the viewcontroller:

// VideoChatViewController.m
// Created by Anand Patel @swayaminfotech
// Copyright (c) Realstir
// All rights reserved.

#import "VideoChatViewController.h"
@interface VideoChatViewController ()<MJSecondPopupDelegate>{

    IBOutlet UIImageView *imgStatusOnlineTitle;
    IBOutlet UIButton *btnBack;
    IBOutlet UIButton *btnEndOfCall;
    IBOutlet UIButton *btnCallingProcess;
    IBOutlet UIButton *btnChangeCamera;
    IBOutlet UIButton *menubtn;
    IBOutlet UILabel *lblChatTime;
    IBOutlet UILabel *lblOnlineNow;

    NSTimer *timeCouter;
    NSTimer *refreshTimer;
    NSDate *todayDate;

    IBOutlet UIButton *callButton;
    IBOutlet UILabel *ringigngLabel;

    IBOutlet QBRTCRemoteVideoView *opponentVideoView;
    IBOutlet UIImageView *myVideoView;
    IBOutlet UIButton *userNamebtn;
    IBOutlet UISegmentedControl *audioOutput;
    IBOutlet UISegmentedControl *videoOutput;
    IBOutlet MarqueeLabel *userNameLabel;

    AVAudioPlayer *ringingPlayer;
    NSUInteger videoChatOpponentID;
    //enum QBVideoChatConferenceType videoChatConferenceType;
    NSString *sessionID;
    UIActivityIndicatorView *callingActivityIndicator;
    UIActivityIndicatorView *startingCallActivityIndicator;

    //Footer
    IBOutlet UIView *tabBarView;
    IBOutlet UIButton *tabHomeValue;
    IBOutlet UIButton *tabChat;
    IBOutlet UIButton *tabSearch;
    IBOutlet UIButton *tabNewsfeed;
    IBOutlet UIButton *tabProfile;
}

@property (strong) UIAlertView *callAlert;
@property (strong) NSString *videoCatName;
@property (strong, nonatomic) QBRTCCameraCapture *videoCapture;

//Header
- (IBAction)headerBack:(id)sender;
- (IBAction)muteMutedAction:(id)sender;
- (IBAction)changeCameraAction:(id)sender;
- (IBAction)messageRedirect:(id)sender;
- (IBAction)call:(id)sender;
- (void)reject;
- (void)accept;
@end

@implementation VideoChatViewController
@synthesize opponentID;
@synthesize isFromOtherViews;
@synthesize videoChatConferenceType;
@synthesize videoChatOpponentID;
@synthesize sessionID;
@synthesize dialog;

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

#pragma mark - View LifeCycle
- (void)viewDidLoad{

    [super viewDidLoad];
    [Util setBorderonButton:tabBarView];
    userNameLabel.text = self.opponentUserName;

    audioOutput.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.8, 0.8);
    audioOutput.frame = CGRectMake(audioOutput.frame.origin.x-15, audioOutput.frame.origin.y, audioOutput.frame.size.width+50, audioOutput.frame.size.height);
    videoOutput.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.8, 0.8);

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appdidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

    //Online Offline
    NSUInteger oppoID = [opponentID integerValue];
    QBUUser *otherUser = [[[LocalStorageService shared] usersAsDictionary] objectForKey:@(oppoID)];

    imgStatusOnlineTitle.layer.cornerRadius = 4;
    imgStatusOnlineTitle.layer.masksToBounds = YES;

    if([Util isUserOffline:otherUser]){
        lblOnlineNow.text = localizeString(@"status_offline");
        imgStatusOnlineTitle.image = [UIImage imageNamed:@""];
        imgStatusOnlineTitle.backgroundColor = RealStirColor;
    }else{
        lblOnlineNow.text = localizeString(@"status_online");
        imgStatusOnlineTitle.image = [UIImage imageNamed:@"V_indic"];
        imgStatusOnlineTitle.backgroundColor = [UIColor clearColor];
    }

    hideNavigationBar;

    if (IS_IPHONE_6_PLUS || IS_IPHONE_6)
        imgStatusOnlineTitle.frame = CGRectMake(130, 39, 8, 8);

    userNameLabel = [Util setMarqueeProperty:userNameLabel];
    [QBRTCClient initializeRTC];
    [[QBRTCClient instance] addDelegate:self]; // self class must conform to QBRTCClientDelegate protocol
}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    kAppDelegate.currentView = @"VideoChatViewController";
    if ([Server checkForInternetConnection]){
        [refreshTimer invalidate];
        refreshTimer = nil;
        refreshTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(refreshMessage) userInfo:nil repeats:YES];

        QBRTCVideoFormat *videoFormat = [[QBRTCVideoFormat alloc] init];
        videoFormat.frameRate = 30;
        videoFormat.pixelFormat = QBRTCPixelFormat420f;
        videoFormat.width = 640;
        videoFormat.height = 480;

        // QBRTCCameraCapture class used to capture frames using AVFoundation APIs
        self.videoCapture = [[QBRTCCameraCapture alloc] initWithVideoFormat:videoFormat position:AVCaptureDevicePositionFront]; // or AVCaptureDevicePositionBack

        // add video capture to session's local media stream
        // from version 2.3 you no longer need to wait for 'initializedLocalMediaStream:' delegate to do it
        self.session.localMediaStream.videoTrack.videoCapture = self.videoCapture;

        self.videoCapture.previewLayer.frame = myVideoView.bounds;
        [self.videoCapture startSession:nil];

        [myVideoView.layer insertSublayer:self.videoCapture.previewLayer atIndex:0];

    }else
        ALERT(localizeString(@"internet_not_available"));

    opponentVideoView.frame = CGRectMake(0, 113, screenWidth, 220);
    showTabbarMenu;
}

-(void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    [refreshTimer invalidate];
    refreshTimer = nil;
}

- (void)viewDidAppear:(BOOL)animated{

    btnChangeCamera.hidden = YES;
    [super viewDidAppear:animated];

    if ([isFromOtherViews isEqualToString:@"YES"]){
        callButton.enabled = NO;
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideCallAlert) object:nil];
        [self accept];
    }else
        [callButton sendActionsForControlEvents:UIControlEventTouchUpInside];

}

-(void)appdidEnterBackground:(NSNotification*)note{
    if(self.session){
        [self dismissCall];
    }
}

#pragma mark - Flip Camera
-(IBAction)changeCameraAction:(id)sender{
    AVCaptureDevicePosition position = self.videoCapture.position;
    AVCaptureDevicePosition newPosition = position == AVCaptureDevicePositionBack ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;

    // check whether videoCapture has or has not camera position
    // for example, some iPods do not have front camera
    if ([self.videoCapture hasCameraForPosition:newPosition]) {
        self.videoCapture.position = newPosition;
    }
}

#pragma mark - Video Call
- (IBAction)call:(id)sender{

    if ([Server checkForInternetConnection]){

        if(callButton.tag == 101){

            btnCallingProcess.hidden = NO;
            [btnCallingProcess setBackgroundImage:[UIImage imageNamed:@"V_calling"] forState:UIControlStateNormal];
            callButton.tag = 102;

            // Setup video chat
            NSArray *opponentsIDs = @[opponentID];
            QBRTCSession *newSession = [[QBRTCClient instance] createNewSessionWithOpponents:opponentsIDs
                                                                          withConferenceType:QBRTCConferenceTypeVideo];
            [newSession startCall:nil];

            callButton.enabled = NO;

            callingActivityIndicator.hidden = NO;
            ringigngLabel.hidden = NO;
            ringigngLabel.text = localizeString(@"calling_process");
            btnEndOfCall.enabled = YES;

            // play call music
            if(![ringingPlayer isPlaying])
            {
                NSString *path =[[NSBundle mainBundle] pathForResource:@"ringing" ofType:@"wav"];
                NSURL *url = [NSURL fileURLWithPath:path];
                ringingPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
                ringingPlayer.delegate = self;
                ringingPlayer.numberOfLoops =- 1;
                [ringingPlayer setVolume:1.0];
                [ringingPlayer play];
            }

        }else{

            callButton.tag = 101;
            // Finish call
            ringigngLabel.hidden = YES;

            myVideoView.hidden = YES;
            //opponentVideoView.layer.contents = (id)[agentProfilePictureAvtar CGImage];
            //opponentVideoView.image = agentProfilePictureAvtar;
            //opponentVideoView.layer.borderWidth = 1;
            [startingCallActivityIndicator stopAnimating];

            if(self.session){
                [self dismissCall];
            }
        }

    }else
        ALERT(localizeString(@"internet_not_available"));
}

- (void)reject
{
    // Reject call
    [self.session rejectCall:nil];
    self.session = nil;

    // update UI
    callButton.enabled = YES;
    ringigngLabel.hidden = YES;
    myVideoView.layer.borderWidth = 0;

    if([ringingPlayer isPlaying])
        [ringingPlayer stop];
}

- (void)accept{

    NSLog(@"accept");
    btnCallingProcess.hidden = NO;
    [btnCallingProcess setBackgroundImage:[UIImage imageNamed:@"Vi_muted"] forState:UIControlStateNormal];

    [[myVideoView layer] setMasksToBounds:YES];
    myVideoView.layer.borderWidth = 1;
    myVideoView.layer.borderColor = [[UIColor grayColor] CGColor];
    myVideoView.layer.cornerRadius = 5;

    [userNameLabel setText:self.opponentUserName];
    [self.session acceptCall:nil];

    ringigngLabel.hidden = YES;
    callButton.enabled = NO;

    callButton.tag = 102;
    //opponentVideoView.layer.borderWidth = 0;
    [startingCallActivityIndicator startAnimating];

    myVideoView.hidden = NO;
    if([ringingPlayer isPlaying])
        [ringingPlayer stop];

    todayDate = [NSDate date];
    timeCouter = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

- (void)hideCallAlert{

    [self.callAlert dismissWithClickedButtonIndex:0 animated:YES];
    self.callAlert = nil;
    callButton.enabled = YES;
}

#pragma mark - Timer Coutdown
-(void) updateCountdown{

    lblChatTime.hidden = NO;

    btnEndOfCall.enabled = YES;
    ringigngLabel.hidden = NO;
    ringigngLabel.text = @"connected";
    btnChangeCamera.hidden = NO;
    //opponentVideoView.backgroundColor = [UIColor blackColor];

    NSDate *now = [NSDate date];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:todayDate toDate:now options:0];

    NSString *stringTimer;
    NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:todayDate];
    NSString *timeRemainIn = @"";

    if (distanceBetweenDates > 86400){

        timeRemainIn = @"day";
        stringTimer = [NSString stringWithFormat:@"%02ld:%02ld:%02ld:%02ld",(long)componentsDaysDiff.day,(long)componentsDaysDiff.hour,(long)componentsDaysDiff.minute,(long)componentsDaysDiff.second];

    }else if (distanceBetweenDates > 3600){

        timeRemainIn = @"hour";
        stringTimer = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)componentsDaysDiff.hour,(long)componentsDaysDiff.minute,(long)componentsDaysDiff.second];

    }else if (distanceBetweenDates > 60){

        timeRemainIn = @"min";
        stringTimer = [NSString stringWithFormat:@"%02ld:%02ld",(long)componentsDaysDiff.minute,(long)componentsDaysDiff.second];

    }else{

        timeRemainIn = @"sec";
        stringTimer = [NSString stringWithFormat:@"%02ld:%02ld",(long)componentsDaysDiff.minute,(long)componentsDaysDiff.second];
    }
    lblChatTime.text = [NSString stringWithFormat:@"%@ %@",stringTimer,timeRemainIn];
}

#pragma mark - Muted-Mute
-(IBAction)muteMutedAction:(id)sender{

    if (![[btnCallingProcess currentBackgroundImage] isEqual:[UIImage imageNamed:@"V_calling"]]){
        /*
        if (self.videoChat.useHeadphone == YES){
            self.videoChat.useHeadphone = NO;
            [btnCallingProcess setBackgroundImage:[UIImage imageNamed:@"Vi_muted"] forState:UIControlStateNormal];
        }else{
            self.videoChat.useHeadphone = YES;
            [btnCallingProcess setBackgroundImage:[UIImage imageNamed:@"Vi_mute"] forState:UIControlStateNormal];
        }*/
    }
}

#pragma mark -
#pragma mark AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

    if([ringingPlayer isPlaying])
        [ringingPlayer stop];
}

#pragma mark - QBRTCClientDelegate

-(void)didReceiveNewSession:(QBRTCSession *)session userInfo:(NSDictionary<NSString *,NSString *> *)userInfo{
    if (self.session) {
        [session rejectCall:nil];
        return;
    }
    self.session = session;
    if ([kAppDelegate.currentView isEqualToString:@"VideoChatViewController"]){

        NSDictionary *chatNotificationData = userInfo;
        NSUInteger userID = [[chatNotificationData objectForKey:@"KuserID"] integerValue];
        NSString *_sessionID = [NSString stringWithFormat:@"%@",[chatNotificationData objectForKey:@"ksessionID"]];
        int conferenceType = [[chatNotificationData objectForKey:@"kconferenceType"] intValue];

        videoChatOpponentID = userID;
        //videoChatConferenceType = conferenceType;
        sessionID = _sessionID;
        callButton.enabled = NO;

        if (self.callAlert == nil){
            [Util getUserPictureObj:[NSString stringWithFormat:@"%ld",userID] completion:^(NSDictionary *response, NSError *error){

                NSMutableDictionary *userObj = [response mutableCopy];
                NSString *displayName = [NSString stringWithFormat:@"%@ %@",[userObj objectForKey:@"FirstName"],[userObj objectForKey:@"LastName"]];
                self.opponentUserName = displayName;

                NSString *message = [NSString stringWithFormat:@"%@%@",displayName,@" Calling"];
                self.callAlert = [[UIAlertView alloc] initWithTitle:@"Call" message:message delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
                self.callAlert.tag = 666;
                [self.callAlert show];

                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideCallAlert) object:nil];
                [self performSelector:@selector(hideCallAlert) withObject:nil afterDelay:4];
            }];
        }
    }
}

- (void)session:(QBRTCSession *)session acceptedByUser:(NSNumber *)userID userInfo:(NSDictionary *)userInfo {
    NSLog(@"Accepted by user %@", userID);
    [[myVideoView layer] setMasksToBounds:YES];
    myVideoView.layer.borderWidth = 1;
    myVideoView.layer.borderColor = [[UIColor grayColor] CGColor];
    myVideoView.layer.cornerRadius = 5;

    btnCallingProcess.hidden = NO;
    [btnCallingProcess setBackgroundImage:[UIImage imageNamed:@"Vi_muted"] forState:UIControlStateNormal];

    ringigngLabel.hidden = NO;
    ringigngLabel.text = @"connected";
    callingActivityIndicator.hidden = YES;
    //opponentVideoView.layer.borderWidth = 0;

    callButton.enabled = YES;
    callButton.tag = 102;
    myVideoView.hidden = NO;
    [startingCallActivityIndicator startAnimating];

    todayDate = [NSDate date];
    timeCouter = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];

    if([ringingPlayer isPlaying])
        [ringingPlayer stop];
}

- (void)session:(QBRTCSession *)session rejectedByUser:(NSNumber *)userID userInfo:(NSDictionary *)userInfo  {
    NSLog(@"Rejected by user %@", userID);
    callButton.enabled = YES;
    ringigngLabel.hidden = YES;
    btnChangeCamera.hidden = YES;
    btnCallingProcess.hidden = YES;
    btnEndOfCall.enabled = NO;
    myVideoView.layer.borderWidth = 0;
    btnCallingProcess.hidden = YES;
    //opponentVideoView.backgroundColor = [UIColor whiteColor];
    [UIApplication sharedApplication].idleTimerDisabled = NO;

    if([ringingPlayer isPlaying])
        [ringingPlayer stop];

    callingActivityIndicator.hidden = YES;
    [NSTimer scheduledTimerWithTimeInterval:30 target:[QBChat instance] selector:@selector(sendPresence) userInfo:nil repeats:YES];
    callButton.tag = 101;

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"VideoChat" message:localizeString(@"m_uesr_call_reject") delegate:self cancelButtonTitle:localizeString(@"close") otherButtonTitles:nil];
    alert.tag = 555;
    [alert show];
}

- (void)session:(QBRTCSession *)session startedConnectingToUser:(NSNumber *)userID {
    NSLog(@"Started connecting to user %@", userID);
}

- (void)session:(QBRTCSession *)session connectionClosedForUser:(NSNumber *)userID {
    NSLog(@"Connection is closed for user %@", userID);
    if(videoChatOpponentID == userID.intValue){
        self.session = nil;
    }
}

- (void)session:(QBRTCSession *)session connectedToUser:(NSNumber *)userID {
    NSLog(@"Connection is established with user %@", userID);
    [startingCallActivityIndicator stopAnimating];
    if ([ringingPlayer isPlaying]){
        [ringingPlayer stop];
    }
}

- (void)session:(QBRTCSession *)session disconnectedFromUser:(NSNumber *)userID {
    NSLog(@"Disconnected from user %@", userID);
}

- (void)session:(QBRTCSession *)session userDidNotRespond:(NSNumber *)userID {
    NSLog(@"User %@ did not respond to your call within timeout", userID);
    callButton.enabled = YES;
    ringigngLabel.hidden = YES;
    callingActivityIndicator.hidden = YES;
    btnEndOfCall.enabled = NO;
    callButton.tag = 101;
    myVideoView.layer.borderWidth = 0;
    btnCallingProcess.hidden = YES;
    //opponentVideoView.backgroundColor = [UIColor whiteColor];

    if([ringingPlayer isPlaying])
        [ringingPlayer stop];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:localizeString(@"m_uesr_call_not_answer") message:nil delegate:self cancelButtonTitle:localizeString(@"close") otherButtonTitles:nil];
    alert.tag = 555;
    [alert show];
}

- (void)session:(QBRTCSession *)session connectionFailedForUser:(NSNumber *)userID {
    NSLog(@"Connection has failed with user %@", userID);
}

- (void)session:(QBRTCSession *)session didChangeState:(QBRTCSessionState)state {
    NSLog(@"Session did change state to %tu", state);
}

- (void)session:(QBRTCSession *)session didChangeConnectionState:(QBRTCConnectionState)state forUser:(NSNumber *)userID {
    NSLog(@"Session did change state to %tu for userID %@", state, userID);
}

- (void)session:(QBRTCSession *)session receivedRemoteVideoTrack:(QBRTCVideoTrack *)videoTrack fromUser:(NSNumber *)userID {
    //opponentVideoView.hidden = NO;
    //[opponentVideoView setContentMode:UIViewContentModeScaleAspectFit];
    //opponentVideoView.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [opponentVideoView setVideoTrack:videoTrack];
}

- (void)session:(QBRTCSession *)session receivedRemoteAudioTrack:(QBRTCAudioTrack *)audioTrack fromUser:(NSNumber *)userID {

    // mute specific user audio track here (for example)
    // you can also always do it later by using '[QBRTCSession remoteAudioTrackWithUserID:]' method
    audioTrack.enabled = NO;
}

- (void)session:(QBRTCSession *)session hungUpByUser:(NSNumber *)userID userInfo:(NSDictionary *)userInfo {
    /**
     HangUp when initiator ended a call
     */
    if ([session.initiatorID isEqualToNumber:userID]) {
        [session hangUp:@{}];
    }
}

- (void)sessionDidClose:(QBRTCSession *)session {

    // release session instance
    self.session = nil;
}

- (void)chatCallDidStopByUserNotification:(NSNotification *)notification{

    NSDictionary *chatNotificationData = notification.userInfo;
    NSString *status = [NSString stringWithFormat:@"%@",[chatNotificationData objectForKey:@"Kstatus"]];

    /*if([status isEqualToString:kStopVideoChatCallStatus_OpponentDidNotAnswer]){

        [self.callAlert dismissWithClickedButtonIndex:0 animated:YES];
        self.callAlert = nil;

        ringigngLabel.hidden = YES;
        if([ringingPlayer isPlaying])
            [ringingPlayer stop];

    }else{

        myVideoView.hidden = YES;
        opponentVideoView.layer.contents = (id)[agentProfilePictureAvtar CGImage];
        opponentVideoView.layer.borderWidth = 1;
        callButton.tag = 101;
    }*/

    //opponentVideoView.backgroundColor = [UIColor whiteColor];
    myVideoView.layer.borderWidth = 0;
    [timeCouter invalidate];
    timeCouter = nil;
    lblChatTime.hidden = NO;
    btnEndOfCall.enabled = NO;
    ringigngLabel.hidden = YES;
    btnChangeCamera.hidden = YES;
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    myVideoView.layer.borderWidth = 0;
    btnCallingProcess.hidden = YES;
    callButton.enabled = YES;
    //[[QBChat instance] unregisterVideoChatInstance:self.videoChat];
    //self.videoChat = nil;
    [self backToListView];
}

#pragma mark UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (alertView.tag == 555){

        [self backToListView];

    }else if (alertView.tag == 666){

        switch (buttonIndex)
        {
            case 0:
                //self.videoChat = nil;
                [self reject];
                break;

            case 1:
                [self accept];
                break;

            default:
                break;
        }
    }
}

-(void)backToListView{

    NSInteger index = -1;
    UINavigationController *navigationController = [kAppDelegate navigationController];
    NSArray* arr = [[NSArray alloc] initWithArray:navigationController.viewControllers];

    for(int i=0 ; i<[arr count] ; i++){
        if([[arr objectAtIndex:i] isKindOfClass:NSClassFromString(@"UsersChatList")]){
            index = i;
        }
    }

    [self.navigationController popToViewController:[arr objectAtIndex:index] animated:YES];
}

- (IBAction)doneButtonAction:(id)sender{

    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

-(IBAction)Dissmis_Call:(id)sender{
    [self dismissCall];
    [self backToListView];
}

-(void)dismissCall{

    myVideoView.layer.borderWidth = 0;
    myVideoView.layer.borderWidth = 0;
    [timeCouter invalidate];
    timeCouter = nil;
    lblChatTime.hidden = NO;
    btnEndOfCall.enabled = NO;
    ringigngLabel.hidden = YES;
    btnChangeCamera.hidden = YES;
    btnCallingProcess.hidden = YES;
    //opponentVideoView.backgroundColor = [UIColor whiteColor];

    [UIApplication sharedApplication].idleTimerDisabled = NO;
    callButton.enabled = YES;
    callButton.tag = 101;

    if ([ringingPlayer isPlaying])
        [ringingPlayer stop];

    myVideoView.hidden = YES;
    //opponentVideoView.layer.contents = (id)[agentProfilePictureAvtar CGImage];
    //opponentVideoView.image = agentProfilePictureAvtar;
    //opponentVideoView.layer.borderWidth = 1;

    [startingCallActivityIndicator stopAnimating];
    if(self.session){
        [self.session hangUp:nil];
    }
    self.session = nil;
}

#pragma mark - Header Actions
- (IBAction)headerBack:(id)sender{
    if(self.session){
        [self dismissCall];
    }
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - Refreshing present
-(void)refreshMessage{

    [[QBChat instance] sendPresenceWithStatus:@""];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self headerStatusCalculate];
        [self request];
    });
}

-(void)request{

    NSMutableDictionary *extendedRequest = [NSMutableDictionary new];
    extendedRequest[@"limit"] = @(100);
    //[QBChat dialogsWithExtendedRequest:extendedRequest delegate:self];
    [QBRequest dialogsForPage:[QBResponsePage responsePageWithLimit:100] extendedRequest:nil successBlock:^(QBResponse * _Nonnull response, NSArray<QBChatDialog *> * _Nonnull dialogs, NSSet<NSNumber *> * _Nonnull dialogsUsersIDs, QBResponsePage * _Nonnull page) {
        NSLog(@"Response: %@",response);
    } errorBlock:^(QBResponse * _Nonnull response) {
        NSLog(@"ERROR: %@",response);
    }];
}

/*
- (void)completedWithResult:(Result *)result{

    if (result.success && [result isKindOfClass:[QBDialogsPagedResult class]]){

        QBDialogsPagedResult *pagedResult = (QBDialogsPagedResult *)result;
        QBGeneralResponsePage *pagedRequest = [QBGeneralResponsePage responsePageWithCurrentPage:0 perPage:100];

        //Unread message Count
        NSMutableArray *dialogs = [pagedResult.dialogs mutableCopy];
        unsigned long totalunreadmessagesCount = 0;
        kCommon.unReadMessagesArr = [[NSMutableArray alloc]init];

        for (QBChatDialog *chatDialog in dialogs){
            totalunreadmessagesCount = totalunreadmessagesCount+[chatDialog unreadMessagesCount];
            if ([chatDialog unreadMessagesCount] != 0)
                [kCommon.unReadMessagesArr addObject:chatDialog];
        }

        kCommon.unReadMessageCount = [NSString stringWithFormat:@"%lu",totalunreadmessagesCount];
        NSSet *dialogsUsersIDs = pagedResult.dialogsUsersIDs;

        if (dialogsUsersIDs.count != 0){

            [QBRequest usersWithIDs:[dialogsUsersIDs allObjects] page:pagedRequest successBlock:^(QBResponse *response, QBGeneralResponsePage *page, NSArray *users){

                 [LocalStorageService shared].users = users;
                 [kAppDelegate stopLoader];
             }errorBlock:nil];
        }
    }
}
*/
-(void)headerStatusCalculate{

    NSUInteger oppoID = [opponentID integerValue];
    QBUUser *otherUser = [[[LocalStorageService shared] usersAsDictionary] objectForKey:@(oppoID)];

    dispatch_async(dispatch_get_main_queue(), ^{
        if([Util isUserOffline:otherUser]){
            lblOnlineNow.text = localizeString(@"status_offline");
            imgStatusOnlineTitle.image = [UIImage imageNamed:@""];
            imgStatusOnlineTitle.backgroundColor = RealStirColor;
        }else{
            lblOnlineNow.text = localizeString(@"status_online");
            imgStatusOnlineTitle.image = [UIImage imageNamed:@"V_indic"];
            imgStatusOnlineTitle.backgroundColor = [UIColor clearColor];
        }
    });
}

#pragma mark - Green Chat Icon
- (IBAction)messageRedirect:(id)sender{

    if(self.session){
        [self dismissCall];
    }

    PrivateChatViewController *conversation = [[PrivateChatViewController alloc]initWithNibName:@"PrivateChatViewController" bundle:nil];
    conversation.chatWithUser = userNameLabel.text;

    if (self.dialog){
        conversation.dialog = self.dialog;
    }

    conversation.isHideBack = @"0";
    [self.navigationController pushViewController:conversation animated:NO];
}

#pragma mark - FooterView
-(IBAction)tabBarAction:(id)sender{

    if (sender == tabHomeValue){

        if ([kCommon.userLoginType isEqualToString:@"1"]){

            PostOneViewController *postView = [[PostOneViewController alloc] initWithNibName:@"PostOneViewController" bundle:nil];
            [self.navigationController pushViewController:postView animated:NO];

        }else{

            HomeValueFormView *homeValueVW = [[HomeValueFormView alloc]initWithNibName:@"HomeValueFormView" bundle:nil];
            [self.navigationController pushViewController:homeValueVW animated:NO];

        }

    }else if (sender == tabChat){

        if(kCommon.strAccessToken.length == 0){

            LoginViewController *loginVW = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
            loginVW.whereRedirect = @"Chat";
            [self.navigationController pushViewController:loginVW animated:NO];

        }else{

            if ([kCommon.isStartQuickblox isEqualToString:@"NO"]){
                [kAppDelegate showLoader];
                [kAppDelegate quicbloxRegistration_completionBlock:^(NSError *error) {
                }];

            }else{

                UsersChatList *chatlist = [[UsersChatList alloc]initWithNibName:@"UsersChatList" bundle:nil];
                [self.navigationController pushViewController:chatlist animated:NO];
            }
        }

    }else if (sender == tabSearch){

        if (IS_OS_8_OR_LATER){

            kCommon.isSearchFromTab = YES;
            [self.navigationController popToRootViewControllerAnimated:NO];

        }else{

            ViewController *searchView = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
            [self.navigationController pushViewController:searchView animated:NO];

        }

    }else if (sender == tabNewsfeed){

        NewsFeedView *newsfeed = [[NewsFeedView alloc]initWithNibName:@"NewsFeedView" bundle:nil];
        [self.navigationController pushViewController:newsfeed animated:NO];

    }else if (sender == tabProfile){

        if(kCommon.strAccessToken.length == 0){

            LoginViewController *loginVW = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
            loginVW.whereRedirect = @"Profile";
            [self.navigationController pushViewController:loginVW animated:NO];

        }else{

            if ([kCommon.userLoginType isEqualToString:@"1"]){

                MyPersonalProfileView *aboutShowViewController = [[MyPersonalProfileView alloc]initWithNibName:@"MyPersonalProfileView" bundle:nil];
                [self.navigationController pushViewController:aboutShowViewController animated:NO];

            }else{

                ConsumerProfile *myprofile = [[ConsumerProfile alloc]initWithNibName:@"ConsumerProfile" bundle:nil];
                [self.navigationController pushViewController:myprofile animated:NO];

            }
        }
    }
}
@end
ghost commented 6 years ago

Hi @jlubeck, move this code:

     // add video capture to session's local media stream
        // from version 2.3 you no longer need to wait for 'initializedLocalMediaStream:' delegate to do it
        self.session.localMediaStream.videoTrack.videoCapture = self.videoCapture;

from view will appear into:

- (IBAction)call:(id)sender{

    if ([Server checkForInternetConnection]){

        if(callButton.tag == 101){

            btnCallingProcess.hidden = NO;
            [btnCallingProcess setBackgroundImage:[UIImage imageNamed:@"V_calling"] forState:UIControlStateNormal];
            callButton.tag = 102;

            // Setup video chat
            NSArray *opponentsIDs = @[opponentID];
            QBRTCSession *newSession = [[QBRTCClient instance] createNewSessionWithOpponents:opponentsIDs
                                                                          withConferenceType:QBRTCConferenceTypeVideo];
///->>>>>>>>>>>  
            newSession.localMediaStream.videoTrack.videoCapture = self.videoCapture;
            [newSession startCall:nil];
///->>>>>>>>>>> and retain new session
            self.session = newSession;
....

Thanks

ghost commented 6 years ago

@jlubeck because you create the session in the call: method, in view will appear session == nil. Plese chek it.

ghost commented 6 years ago

Please check our video sample. We set video capture for local media stream after session creates.

Thanks.

ghost commented 6 years ago

Hi @jlubeck, Any updates?

jlubeck commented 6 years ago

Working on it!

jlubeck commented 6 years ago

It worked!!! But instead of moving from viewWillAppear I had to copy it it. If I just moved it, then it work the other way around and only work on the receiver and not the caller. Thanks!