Tuesday, December 13, 2016

UIText Field With Image on left side

UITextField with image and bottom border


UITextField *txtVideoLink=[[UITextField alloc] initWithFrame:CGRectMake(10, y, SCREEN_WIDTH-20, 50)];
            UIView *paddingView3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            txtVideoLink.tintColor = [UIColor darkGrayColor];
            txtVideoLink.leftView = paddingView3;
            txtVideoLink.autocorrectionType = UITextAutocorrectionTypeNo;
            txtVideoLink.placeholder=@"Video Link";
            NSString *linkType = newsObj.VideoUrl;
            if(fromList)
            {
                if([linkType containsString:@"yt"] || [linkType containsString:@"youtube"])
                    txtVideoLink.text = newsObj.VideoUrl;
            }
            txtVideoLink.delegate = self;
            txtVideoLink.tag = 3;
            txtVideoLink.returnKeyType = UIReturnKeyDone;
            txtVideoLink.font=[UIFont fontWithName:AppFont size:fontSize12];
            txtVideoLink.keyboardType=UIKeyboardTypeDefault;
            //Boarder Bottom Row
            CALayer *border3 = [CALayer layer];
            border3.borderColor =  [UIColor lightGrayColor].CGColor;
            border3.frame = CGRectMake(0, txtVideoLink.frame.size.height - borderWidth, txtVideoLink.frame.size.width, txtVideoLink.frame.size.height);
            border3.borderWidth = borderWidth;
            [txtVideoLink.layer addSublayer:border3];
            txtVideoLink.layer.masksToBounds = YES;
            
            UIImageView *imgSearch3=[[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 20, 20)]; // Set frame as per space required around icon
            
            [imgSearch3 setImage:[UIImage imageNamed:@"clipping.png"]];
            imgSearch3.backgroundColor = [UIColor clearColor];
            [imgSearch3 setContentMode:UIViewContentModeCenter];// Set content mode centre
            imgSearch3.contentMode = UIViewContentModeScaleAspectFill;
            txtVideoLink.leftView = imgSearch3;
            txtVideoLink.leftViewMode=UITextFieldViewModeAlways;

            [scrollView addSubview:txtVideoLink];

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];
}




Validate Email address in iOS

Email address Validation 

- (BOOL)validateEmailWithString:(NSString*)checkString
{
    BOOL stricterFilter = NO;
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];

}

Upload gallery or camera picture to server in iOS



User can select picture from camera or from gallery 

///Select Picture from Gallery 
-(IBAction)pickGalleryImage:(id)sender
{
    imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.delegate = self;
    imagePickerController.navigationBar.tintColor = [UIColor blackColor];
    [self presentViewController:imagePickerController animated:YES completion:nil];
    imagePickerMenu.hidden=true;
    [imagePickerMenu removeFromSuperview];
    [viewMain removeFromSuperview];
}


///Select Picture from Camera
-(IBAction)pickCameraImage:(id)sender
{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init] ;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //Permetto la modifica delle foto
    picker.allowsEditing = YES;
    //Imposto il delegato
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    //[self presentModalViewController:picker animated:YES];
    imagePickerMenu.hidden=true;
    [imagePickerMenu removeFromSuperview];
    [viewMain removeFromSuperview];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    CGSize imgSize =CGSizeMake(200, 200);
    UIImage *image = [self imageWithImage:[info objectForKey:UIImagePickerControllerOriginalImage] scaledToSize:imgSize];
   
//Image Compression
    NSData * imageData = UIImageJPEGRepresentation(image, 0.70);
    NSLog(@"lenght %.2lu", (unsigned long)imageData.length);
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"MMddYYYY_HHmmss"];
    NSString *lstrCurrentDatetime = [formatter stringFromDate:[NSDate date]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    //creating image name
    NSString *uId = @"1";
    NSString *strImageName = [@"" stringByAppendingFormat:@"User_Profile_%@_%@.jpeg", uId,lstrCurrentDatetime ];
    
    //saving to doc directory
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:strImageName];
    [imageData writeToFile:savedImagePath atomically:NO];
    
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [self uploadGalleryImage:strImageName];
}

//Resize Image
-(UIImage*)imageWithImage:(UIImage*)image
             scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext( CGSizeMake(200, 200) );
    [image drawInRect:CGRectMake(0,0,200,200)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark - Image Upload -
-(void)uploadGalleryImage:(NSString *)imgProfilePic
{

    NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [docpaths objectAtIndex:0];
    NSString *serviceUrl = [NSString stringWithFormat:@"%@UploadProfilePic.php",kImageUpLoadURL];
    
    // an url where the request to be posted
    NSURL *url = [NSURL URLWithString:serviceUrl];
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc] initWithURL:url] ;
    
    [request setURL:[NSURL URLWithString:serviceUrl]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:imgProfilePic];
    NSMutableDictionary *dictUpload = [[NSMutableDictionary alloc] init];
    
    NSMutableData *postbody = [NSMutableData data];
    NSString *postData = [self getHTTPBodyParamsFromDictionary:dictUpload boundary:boundary];
    [postbody appendData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:imagePath]];
    UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
    NSData *imageData = UIImageJPEGRepresentation(thumbNail, 0.60);
    NSLog(@"lenght %lu", (unsigned long)[imageData length]);
    
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\";  filename=\"%i%@\"\r\n", 1, imgProfilePic] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [postbody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:imageData]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];
   
    NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
                                                                  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                   {
                                       if(data == nil){
                                           NSLog(@"Upload Failure");
                                           [SVProgressHUD dismiss];
                                           [self CallAlert:appName andMsg:@"Image could not be uploaded please try again or late"];
                                       }
                                       
                                       returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                       
                                       if([returnString containsString:@"Success"])
                                       {
                                           [SVProgressHUD dismiss];
                                           profileImage = [returnString stringByReplacingOccurrencesOfString:@"Success." withString:@""];
                                           NSString *newStr=[kProfileImagePath stringByAppendingFormat:@"%@",profileImage];
                                           NSURL *imgUrl=[NSURL URLWithString:newStr];
                                           [imgProfile sd_setImageWithURL:imgUrl];
                                       }
                                       
                                      // [SVProgressHUD dismiss];
                                   }];
                    [dataTask resume];
    
}

-(NSString *) getHTTPBodyParamsFromDictionary: (NSDictionary *)params boundary:(NSString *)boundary
{
    NSMutableString *tempVal = [[NSMutableString alloc] init];
    for(NSString * key in params)
    {
        [tempVal appendFormat:@"\r\n--%@\r\n", boundary];
        [tempVal appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@",key,[params objectForKey:key]];
    }
    return [tempVal description];

}

Upload UIImage as base64 String

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