Monday, August 15, 2011

Download Data From The Web

Designing the User Interface:- 




#import <UIKit/UIKit.h>

@interface DownloadViewController : UIViewController <UITextFieldDelegate>{
    UITextField *urlName;
    UIProgressView *progressView;
    UILabel *progressLabel;
    NSMutableData *receivedData;
    long DownloadingLength;
}

@property (nonatomic, retain) IBOutlet UILabel *progressLabel;
@property (nonatomic, retain) IBOutlet UIProgressView *progressView;
@property (nonatomic, retain) IBOutlet UITextField *urlName;


-(IBAction)startDownload;
-(void)saveData:(NSMutableData*)data toFile:(NSString*)file;

@end
The progressLabel has to show how many bytes have been downloaded and the progressView shows the progress of the download.
The user has to paste in the URL, of the data on the web, into the urlName and click on the button to download the data.
We declare one simple IBAction, that gets called, when the download finishes and a method to save the data with a given name into the documents directory.
nIn .m file 

@synthesize urlName, progressView, progressLabel;
Implementing the NSURLDelegate
Then we have to implement the IBAction we’ve declared in the header file :
-(IBAction)startDownload {
    progressLabel.text = @"0 Bytes";
    progressView.progress = 0.0f;
    NSURL *url = [[NSURL alloc] initWithString:urlName.text];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true];
    [connection release];
    [request release];
    [url release];
    receivedData = [[NSMutableData alloc] init];
}
Ok. The next thing we have to do is to implement the needed methods from the NSURLConnection delegate :


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if (data != nil) {
        [receivedData appendData:[[NSData alloc] initWithData:data]];  
    }
    progressLabel.text = [NSString stringWithFormat:@"%d Bytes",[receivedData length]];
    if (DownloadingLength <= 0) {
        return;
    }
        
float a = [receivedData length];
    float b = DownloadingLength;
    NSNumber *progress = [NSNumber numberWithFloat:a/b];
   
    progressView.progress = [progress floatValue];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Downloading not Completed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];
    [alert release];
    [receivedData release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Download complete" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];
    [alert release];
    [self saveData:receivedData toFile:@"vijay.dat"];
    [receivedData release];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    DownloadingLength = [response expectedContentLength];
}
The SaveToFile Method
Now there’s only one thing left.
The save method :
-(void)saveData:(NSMutableData *)data toFile:(NSString *)file {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true);
    NSString *temp = [paths objectAtIndex:0];
    temp = [temp stringByAppendingPathComponent:file];
    [data writeToFile:temp atomically:true];
}

Monday, August 1, 2011

Take Photo from iPhone And Upload to server


- (IBAction)TakeImage {

     self.imgPicker = [[UIImagePickerController alloc] init];
    self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imgPicker.allowsImageEditing = YES;
    self.imgPicker.delegate = self;   
    [self presentModalViewController:self.imgPicker animated:YES];
}








- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
   
image.image = img;   
  
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
   
      }



- (IBAction)uploadImage {
   NSData *imageData = UIImageJPEGRepresentation(image.image, 0.1); //Here 0.1 is to compress the image size..
     
  NSString *imgDataStr = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
 
      NSString *urlString = @"Your URL where you want to upload";
   
    // setting up the request object now
  
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
 
  [request setURL:[NSURL URLWithString:urlString]];
  
[request setHTTPMethod:@"POST"];
       
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];



  

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
  

[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
   
    /*
     now lets create the body of the post
     */
   
    NSMutableData *body = [NSMutableData data];
   
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];   
  

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", self.imagename] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
 
  [body appendData:[NSData dataWithData:imageData]];
 
  [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
   
    [request setHTTPBody:body];
 
  NSString *requestDataStr = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
      
    // now lets make the connection to the web
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
 
  NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
   
  }

Take Video from iPhone And Upload to server

-(IBAction)displayCamera :(id)sender
{
 
    BOOL canShootVideo = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
   
    if (canShootVideo) {
        UIImagePickerController *videoRecorder = [[UIImagePickerController alloc] init];
        videoRecorder.sourceType = UIImagePickerControllerSourceTypeCamera;
      
        videoRecorder.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        videoRecorder.videoMaximumDuration = 5;
        BOOL capture = [videoRecorder startVideoCapture];
      
        videoRecorder.delegate = self;
       
        NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF contains %@)", @"movie"]];
        BOOL movieOutputPossible = (videoMediaTypesOnly != nil);
       
        if (movieOutputPossible) {
            videoRecorder.mediaTypes = videoMediaTypesOnly;
           
            [self presentModalViewController:videoRecorder animated:YES];          
        }
        [videoRecorder release];
    }
   
   
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Camera Demo" message:@"Device Lacks Camera" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
       
        [alert show];
        [alert release];
    }
   
}
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
   
      NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
   
    //check the media type string so we can determine if its a video
    if ([mediaType isEqualToString:@"public.movie"]){
               NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
               NSData *webData = [NSData dataWithContentsOfURL:videoURL];
             [self post:webData];
 
       
    }
   
   
}





- (void)post:(NSData *)fileData{
   
    NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: @"Your URL where you want to post video"]];
    [post setHTTPMethod: @"POST"];
   
   
    NSString *boundary = [NSString stringWithString:@"---------------------------358734318367435438734347"];
   
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
   
    [post addValue:contentType forHTTPHeaderField: @"Content-Type"];
   
   
    NSMutableData *body = [NSMutableData data];
   
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   
    //[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"vijay.mpeg\"\r\n", ] dataUsingEncoding:NSUTF8StringEncoding]];

   
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", self.videoName] dataUsingEncoding:NSUTF8StringEncoding]];
   
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   
    [body appendData:fileData];
   
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   
   
    [post setHTTPBody:body];
   
    NSData *returnData = [NSURLConnection sendSynchronousRequest:post returningResponse:nil error:nil];
   
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
   
 
   
}

How to Write in iPad on finger move


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   
    mouseSwiped = NO;
    UITouch *touch = [[event allTouches] anyObject];
   
    lastPoint = [touch locationInView:self.view];
    lastPoint.y -=180;
    lastPoint.x -=90;
    CGPoint location = [touch locationInView:self.view];
    imageView.center = location;

    }


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    mouseSwiped = YES;
       
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];
    imageView.center = location;

       
    {       
        CGPoint currentPoint = [touch locationInView:self.view];
        currentPoint.y -=180;
        currentPoint.x -=90;
       
        UIGraphicsBeginImageContext(drawImage.frame.size);
        [drawImage.image drawInRect:CGRectMake(0, 0, 618, 636)];
       
       
       
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
       
        if (isWritingEnabled) {
            CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);           
        }
         else
{
             CGContextSetLineWidth(UIGraphicsGetCurrentContext(),15);
            CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
        }
        CGContextBeginPath(UIGraphicsGetCurrentContext());
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
       
       
       
        UIGraphicsEndImageContext();
       
        lastPoint = currentPoint;
       
    }
   
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
   
   
        if(!mouseSwiped) {
            UIGraphicsBeginImageContext(drawImage.frame.size);
            [drawImage.image drawInRect:CGRectMake(0, 0, 618, 636)];
            CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
            CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
            CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
            CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
            CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
            CGContextStrokePath(UIGraphicsGetCurrentContext());
            CGContextFlush(UIGraphicsGetCurrentContext());
           
            drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
   
   
}

Sunday, July 31, 2011

Set Colour of searchbar and NavigationBar

[self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:122.0f/255.0f green:165.0f/255.0f blue:156.0f/255.0f alpha:1]];
       
  [self.searchBar setTintColor:[UIColor colorWithRed:122.0f/255.0f green:165.0f/255.0f blue:156.0f/255.0f alpha:1]];
       

How to Customize slider and rotate to 90degrees....

   sliderTransform = YourSlider.transform;

    [YourSlider setFrame:CGRectMake(67.0f, 199.0f, 251.0f,10.0f)];

  YourSlider.transform = CGAffineTransformRotate(sliderTransform, 270.0/180*M_PI);



//This makes YourSlider to vertical

    YourSlider.backgroundColor = [UIColor clearColor];

UIImage *stetchTrack1 = [[UIImage imageNamed:@"blankimage.png"]stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
   
  [YourSlider setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"blueslider.png"]]];


  [YourSlider setThumbImage:[UIImage imageNamed:@"thumb.png"] forState:UIControlStateNormal];  //to set thumb image of Slider

    [YourSlider setMinimumTrackImage:stetchTrack1 forState:UIControlStateNormal];
    [YourSlider setMaximumTrackImage:stetchTrack1 forState:UIControlStateNormal];
   
    YourSlider.continuous = YES;

    [YourSlider setAccessibilityLabel:NSLocalizedString(@"CustomSlider", @"")];

    [self.view addSubview:YourSlider];

Add Done button on Numeric keyBorad....

- (void)textFieldDidBeginEditing:(UITextField *)textField{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow)  name:UIKeyboardWillShowNotification    object:nil];
                                       
}


- (void)keyboardWillShow {

 [self performSelector:@selector(addHideKeyboardButtonToKeyboard) withObject:nil afterDelay:0];
}


- (void)addHideKeyboardButtonToKeyboard {

 // Locate non-UIWindow.

    UIWindow *keyboardWindow = nil;

    UIView *keyboard;

  for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {


        if (![[testWindow class] isEqual:[UIWindow class]]) {
            keyboardWindow = testWindow;
            break;
        }
 }



  if (!keyboardWindow) return;
   
    // Locate UIKeyboard. 
    UIView *foundKeyboard = nil;
    for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
       
        // iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
        if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
            possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
        }                                                                               
       
        if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) {
            foundKeyboard = possibleKeyboard;
            keyboard = possibleKeyboard;
           
            break;
        }
    }
   

if (foundKeyboard) {

        // Add the button to foundKeyboard.
  UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];

  doneButton.frame = CGRectMake(0, 163, 106, 53);

  doneButton.adjustsImageWhenHighlighted = NO;

  [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];

[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];




 [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
       
        // keyboard view found; add the custom button to it


        [keyboard addSubview:doneButton];
    }
   
}

//Now Removing Done button along with keyBoard

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
   
 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  

[self removeDoneButton];
   
 [textField resignFirstResponder];
   
    return YES;

}

-(void)removeDoneButton{
 
  UIWindow *keyboardWindow = nil;
    UIView *keyboard;
    for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
        if (![[testWindow class] isEqual:[UIWindow class]]) {
            keyboardWindow = testWindow;
            break;
        }
    }
    if (!keyboardWindow) return;
   
    // Locate UIKeyboard. 

    UIView *foundKeyboard = nil;


    for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
            if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
           
                           possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
        }                                                                               
       
        if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) {
          

            foundKeyboard = possibleKeyboard;
            keyboard = possibleKeyboard;
           
            break;
        }
    }
   
    if (foundKeyboard) {
     
  // Add the button to foundKeyboard.

        UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];

        doneButton.frame = CGRectMake(0, 163, 106, 53);

        doneButton.adjustsImageWhenHighlighted = NO;
      [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
      [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
     
  [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
       
        // keyboard view found; add the custom button to it

        NSLog(@"keyboard description: %@", [keyboard description]);
     
  for (UIView *v in [keyboard subviews]) {

         if ([v isKindOfClass:NSClassFromString(@"UIButton")]) {

                [v removeFromSuperview];

               }
         }
     }
}