About
Home > Tutorials Home > Ios > How to Upload Files on FTP using Objective C

How to Upload Files on FTP using Objective C

Published on October 17, 2019 8:33:01 PM

We are an online tutoring company that has laid its foundation in utilizing Multiple Intelligence methodology to understand specific needs and learning styles of a student.So that we patch a particular student to a tutor having a compatible teaching style. We have devised a smart online tutoring system to give you measurable results.Schools, cramped with students, fail to give your child the edge, the motivation and the right teacher guidance to help him find the true potential. We at Eonlinetutors.com make sure that your child gets the perfect learning environment to outperform.




Step 1 : Open the XCode and create a new Single View Based Application template. Give the application name "UploadFTPApp". Copy this Code to the ViewController.h and hook up the properties with appropriate control.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <NSStreamDelegate>

@property (nonatomic, strong, readwrite) NSInputStream *fileStream;
@property (nonatomic, strong, readwrite) NSOutputStream *networkStream;
@property (nonatomic, assign, readonly) NSUInteger networkOperationCount;
@property (nonatomic, assign, readwrite) size_t bufferOffset;
@property (nonatomic, assign, readwrite) size_t bufferLimit;
@property (nonatomic, assign, readonly) uint8_t *buffer;
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *process;

- (IBAction)uploadFiles:(id)sender;

@end

Step 2 : Add CFNetworkFramework to you project.


Step 3 : Copy the Following Code into your ViewController.m File.

#import "ViewController.h"

#include <CFNetwork/CFNetwork.h>

enum {
	kSendBufferSize = 32768
};

@interface ViewController ()
{
	uint8_t _buffer[kSendBufferSize];
}
@end

@implementation ViewController
@synthesize process;
@synthesize fileStream;
@synthesize networkStream;
@synthesize bufferOffset;
@synthesize bufferLimit;
@synthesize buffer;

- (void)viewDidLoad {
	[super viewDidLoad];
	[process stopAnimating];
	process.hidden = YES;
}

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

- (IBAction)uploadFiles:(id)sender {
	process.hidden = NO;
	[process startAnimating];
	NSLog(@"Uploading Files");

	if (!self.isSending) {
		NSString *filePath;

		filePath = [[NSBundle mainBundle]pathForResource:@"App" ofType:@"ipa"];

		[self startSend:filePath];
	}
	else
		NSLog(@"Skipped");
}

- (void)startSend:(NSString *)filePath {
	BOOL success;
	NSURL *url;

	url = [NSURL URLWithString:@"ftp://192.168.100.184:21/"];

	success = (url != nil);

	if (success) {
		url = CFBridgingRelease(
		        CFURLCreateCopyAppendingPathComponent(NULL, (__bridge CFURLRef)url, (__bridge CFStringRef)[filePath lastPathComponent], false)
		        );
		success = (url != nil);
	}

	if (!success) {
		UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Invalid URL" message:@"Can not upload file." delegate:nil cancelButtonTitle:@"Okey" otherButtonTitles:nil, nil];
		[alert show];
	}
	else {
		self.fileStream = [NSInputStream inputStreamWithFileAtPath:filePath];
		assert(self.fileStream != nil);

		[self.fileStream open];

		self.networkStream = CFBridgingRelease(
		        CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef)url)
		        );

		//success = [self.networkStream setProperty:@"" forKey:(id)kCFStreamPropertyFTPUserName];
		//success = [self.networkStream setProperty:@"" forKey:(id)kCFStreamPropertyFTPPassword];

		self.networkStream.delegate = self;
		[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
		[self.networkStream open];
	}
}

//Deletegate Events
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
#pragma unused(aStream)
	assert(aStream == self.networkStream);

	switch (eventCode) {
		case NSStreamEventOpenCompleted: {
			NSLog(@"Opened connection");
		} break;

		case NSStreamEventHasBytesAvailable: {
			NSLog(@"NSStreamEventHasBytesAvailable");
		} break;

		case NSStreamEventHasSpaceAvailable: {
			NSLog(@"Sending");

			if (self.bufferOffset == self.bufferLimit) {
				NSInteger bytesRead;

				bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];

				if (bytesRead == -1) {
					NSLog(@"File read error");

					if (self.networkStream != nil) {
						[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
						self.networkStream.delegate = nil;
						[self.networkStream close];
						self.networkStream = nil;
					}
					if (self.fileStream != nil) {
						[self.fileStream close];
						self.fileStream = nil;
					}
				}
				else if (bytesRead == 0) {
					NSLog(@"Upload Complete");
					[process stopAnimating];
					process.hidden = YES;

					if (self.networkStream != nil) {
						[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
						self.networkStream.delegate = nil;
						[self.networkStream close];
						self.networkStream = nil;
					}
					if (self.fileStream != nil) {
						[self.fileStream close];
						self.fileStream = nil;
					}
				}
				else {
					self.bufferOffset = 0;
					self.bufferLimit  = bytesRead;
				}
			}

			if (self.bufferOffset != self.bufferLimit) {
				NSInteger bytesWritten;
				bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
				assert(bytesWritten != 0);
				if (bytesWritten == -1) {
					NSLog(@"Network Write Error");

					if (self.networkStream != nil) {
						[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
						self.networkStream.delegate = nil;
						[self.networkStream close];
						self.networkStream = nil;
					}
					if (self.fileStream != nil) {
						[self.fileStream close];
						self.fileStream = nil;
					}
				}
				else {
					self.bufferOffset += bytesWritten;
				}
			}
		} break;

		case NSStreamEventErrorOccurred: {
			NSLog(@"Stream Open Error");
			[process stopAnimating];
			process.hidden = YES;

			if (self.networkStream != nil) {
				[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
				self.networkStream.delegate = nil;
				[self.networkStream close];
				self.networkStream = nil;
			}
			if (self.fileStream != nil) {
				[self.fileStream close];
				self.fileStream = nil;
			}
		} break;

		case NSStreamEventEndEncountered: {
		} break;

		default: {
			NSLog(@"Default Not found");
		} break;
	}
}

//Code for uploading
- (BOOL)isSending {
	return (self.networkStream != nil);
}

- (uint8_t *)buffer {
	return self->_buffer;
}

@end
ALL COMMENTS (2)
Abhishek Bedre 2017-03-28 17:25:15
I have implemented my own "jarvis"....thanks to this example.        
2019-01-03 13:22:19
It is working fine in desktop but not working in android mobile