Thursday, 5 May 2011

Upload File to FTP Server on iPhone

Implementing the file upload to FTP Server:

I use a PHP Page to upload the file  and have PHP handle the uploading....
This code is used to upload a photo, but it can be adapted to work with any file.
PHP Code:
$uploaddir = 'photos/';
$file = basename($_FILES['userfile']['name']);                    //userfile should give in the iphone server upload code
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "upload success";
} else {
    echo "error uploading";
IPhone Code:
NSData * rfile = [[NSData alloc]initWithContentsOfURL:@"image url / location of your media"];
NSString *urlString = @"";
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"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data;name=\"userfile\"; filename=\"%@\"\r\n",filename]]dataUsingEncoding:NSUTF8StringEncoding]];                                               //userfile should match with your php

[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:rfile]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Response from Server : %@",returnString);

Finally you will get the response as "Upload Success" otherwise show you "Error uploading"
Let me know if you have any queries


Wednesday, 4 May 2011

AvAudioRecorder - Pause and Resume a recording

AVAudioRecorder provides audio recording capability in your application. Using an audio recorder you can:
  • Record until the user stops the recording
  • Record for a specified duration
  • Pause and resume a recording.
You can implement a delegate object for an audio recorder to respond to audio interruptions and audio decoding errors, and to the completion of a recording.
To configure a recording, including options such as bit depth, bit rate, and sample rate conversion quality, configure the audio recorder’ssettings dictionary. Use the settings keys described in AV Foundation Audio Settings Constants.
To configure an appropriate audio session for recording, refer to AVAudioSession Class Reference and AVAudioSessionDelegate Protocol Reference.

Code :

   NSLog(@"Record Start");
if (recorder==nil) {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
[audioSession setActive:YES error:&err];
err = nil;
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
NSString *recorderFilePath = [[NSString stringWithFormat:@"%@/MyRecord.caf",DOCUMENTS_FOLDER] retain];
recordedTmpFile = [NSURL fileURLWithPath:recorderFilePath];
recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&err];
NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning"
  message: [err localizedDescription]
  delegate: nil
[alert show];
[alert release];
//prepare to record
[recorder setDelegate:self];
//[recorder prepareToRecord];
BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning"
  message: @"Audio input hardware not available"
  delegate: nil
[cantRecordAlert show];
[cantRecordAlert release]; 
// start recording
//[recorder recordForDuration:(NSTimeInterval)10];
[recorder record];
     else {
[recorder record];

 [recorder pause];
AVAudioPlayer provides playback of audio data from a file or memory.
Apple recommends that you use this class for audio playback unless you are playing audio captured from a network stream or require very low I/O latency. For an overview of audio technologies, see Getting Started with Audio & Video and “Using Audio” in Multimedia Programming Guide.
Using an audio player you can:
  • Play sounds of any duration
  • Play sounds from files or memory buffers
  • Loop sounds
  • Play multiple sounds simultaneously, one sound per audio player, with precise synchronization
  • Control relative playback level and stereo positioning for each sound you are playing
  • Seek to a particular point in a sound file, which supports such application features as fast forward and rewind
  • Obtain data you can use for playback-level metering
The AVAudioPlayer class lets you play sound in any audio format available in iOS. You implement a delegate to handle interruptions (such as an incoming phone call) and to update the user interface when a sound has finished playing. The delegate methods to use are described inAVAudioPlayerDelegate Protocol Reference.
To play, pause, or stop an audio player, call one of its playback control methods, described in “Configuring and Controlling Playback.”
This class uses the Objective-C declared properties feature for managing information about a sound—such as the playback point within the sound’s timeline, and for accessing playback options—such as volume and looping. You also use a property (playing) to test whether or not playback is in progress.
To configure an appropriate audio session for playback, refer to AVAudioSession Class Reference and AVAudioSessionDelegate Protocol Reference. To learn how your choice of file formats impacts the simultaneous playback of multiple sounds, refer to “iPhone Hardware and Software Audio Codecs” in Multimedia Programming Guide.

// Init audio with playback capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&err];
    [audioPlayer prepareToPlay];
[audioPlayer play];