Tuesday, December 13, 2016

Upload Video to Server in iOS


-(IBAction)uploadVideo:(id)sender
{
    
        [self startCameraControllerFromViewController: self
                                        usingDelegate: self];
}

- (BOOL) startCameraControllerFromViewController: (UIViewController*) controller
                                   usingDelegate: (id <UIImagePickerControllerDelegate,
                                                   UINavigationControllerDelegate>) delegate1 {
    UIImagePickerController *cameraUI = [[UIImagePickerController allocinit];
    
    if(isVideoClicked)
    {
        if (([UIImagePickerController isSourceTypeAvailable:
              UIImagePickerControllerSourceTypeCamera] == NO)
            || (delegate1 == nil)
            || (controller == nil))
            return NO;
        
        
        
        cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
        cameraUI.videoQuality = UIImagePickerControllerQualityTypeLow;
        cameraUI.allowsEditing = NO;
    }
    else
    {
        if (([UIImagePickerController isSourceTypeAvailable:
              UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
            || (delegate1 == nil)
            || (controller == nil))
            return NO;
        
        cameraUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        cameraUI.allowsEditing = YES;
    }
    cameraUI.mediaTypes = [[NSArray allocinitWithObjects: (NSString *) kUTTypeMovienil];
    cameraUI.delegate = delegate1;
    [controller presentViewController:cameraUI animated:YES completion:nil];
    return YES;

}


//Delegate Method

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    selectedVideoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        
    //calling the function to optimize the video to make it lower resolution.
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [self performSelector:@selector(OptimizeVideo) withObject:nil afterDelay:2.0f];
   
    [picker dismissViewControllerAnimated:NO completion:nil];
    //[self uploadGalleryImage:strImageName];
}

-(void)OptimizeVideo
{
    NSString *timeStamp = @"";
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"ddMMyyyyHHmmss"];
    timeStamp = [df stringFromDate:[NSDate date]];
    
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *recorderFilePath1 = [NSString stringWithFormat:@"%@/%@.mov", docDir, timeStamp];
    NSURL *url = [NSURL fileURLWithPath:recorderFilePath1];
    NSString *dataPath;
    //Raj Mohan
    if (![[NSFileManager defaultManager] fileExistsAtPath:recorderFilePath1])
    {
        NSError *error;
        dataPath = [docDir stringByAppendingPathComponent:@"MyVideos"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
        
        NSString *helloStr  = [NSString stringWithFormat:@"%@.mov",timeStamp];;
        videoUrlToDb = [NSURL URLWithString:helloStr];
        [recorderFilePath1 writeToFile:helloStr atomically:YES
                              encoding:NSUTF8StringEncoding error:nil];
        BOOL success = [[NSFileManager defaultManager] removeItemAtPath:recorderFilePath1 error:&error];
        if (success) {
            NSLog(@"deleted file -:%@ ",[error localizedDescription]);
        }
        else
        {
            NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
        }
    }
    
    if ([[NSFileManager defaultManager] isWritableFileAtPath:dataPath]) {
        NSLog(@"Writable");
    }else {
        NSLog(@"Not Writable");
    }
    [self convertVideoToLowQuailtyWithInputURL:selectedVideoURL outputURL:url handler:^(AVAssetExportSession *exportSession)
     {
         if (exportSession.status == AVAssetExportSessionStatusCompleted)
         {
             
             selectedVideoURL = url;
             NSDateFormatter *df = [[NSDateFormatter alloc] init];
             [df setDateFormat:@"MMddyyyyHHmmss"];
             //txtVideoURL.text = [NSString stringWithFormat:@"%@.mp4", timeStamp];
             selFileName = [NSString stringWithFormat:@"%@.mp4", timeStamp];
             [self postVideoToServer];
             
         }
         //}
         else
         {
             [SVProgressHUD dismiss];
             [self CallAlert:appName andMsg:@"Error, please try again."];
         }
         
     }];
    
    
}

#pragma mark Convert the video to lower resolution
- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL
                                   outputURL:(NSURL*)outputURL
                                     handler:(void (^)(AVAssetExportSession*))handler
{
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         handler(exportSession);
         
     }];
    
}

-(void)postVideoToServer
{
    NSData *fileData = [NSData dataWithContentsOfURL:selectedVideoURL];
    NSString *urlString = [kVideoLink stringByAppendingFormat:@"UploadVid.php"];
    
    NSString *timeStamp = @"";
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"ddMMyyyyHHmmss"];
    timeStamp = [df stringFromDate:[NSDate date]];
    
    // NSString *fileName = [[df stringFromDate:[NSDate date]] stringByAppendingString:@".mov"];
    
    
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", selFileName] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [postbody appendData:[NSData dataWithData:fileData]];
    // [postbody appendData:[@"Content-Type: video/mp4\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];
    
    //Ashwani
    
    NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
                                                                      completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                       {
                                           if(data == nil){
                                               
                                               [SVProgressHUD dismiss];
                                               [self CallAlert:appName andMsg:@"Video upload failure."];
                                               return;
                                           }
                                           
                                           NSString *returnVideoString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                           NSArray *Arr =[returnVideoString componentsSeparatedByString:@"#"];
                                           returnString = [Arr objectAtIndex:0];
                                           if([returnString containsString:@"mp4"])
                                           {
                                               isVideoClicked = false;
                                               [SVProgressHUD dismiss];
                                               lblChooseVideo.text = returnString;
                                               ;
                                              // strImagePath =returnVideoString;
                                           }
                                       }];
    [dataTask resume];
}




Upload UIImage as base64 String

Upload UIImage as Base64 String (Upload UIImage as string) //Select Pic From Camera or Gallery       @objc func btnPro...