FTP通信を用いてFTPサーバからCSVファイルをダウンロードしたいと考えています。
ファイルサイズ自体はそこまで大きいサイズでないので、NSURLConectionを用いてダウンロードを行いたいと考えています。
ソースを書き、エラーも吐かなかったのですが、肝心のダウンロードができませんでした。
以下ソースです。
FTP.h
► スポイラーを表示
► スポイラーを表示
#import "FTP.h"
@implementation FTP
- (void)FTPDownload{
NSLog(@"downloadStart");
NSURL *url = [NSURL URLWithString:@"ftp://username:password@sample/naisen.csv"];
if (!url) {
//エラーメッセージを表示する
UIAlertView *alert;
alert = [[UIAlertView alloc]
initWithTitle:@"Error"
message:@"The URL is invalid."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
return;
}
//URLからダウンロードする
NSError *error = nil;
NSData *data;
BOOL isSuccessed = NO;
data = [NSData dataWithContentsOfURL:url
options:0
error:&error];
//ダウンロードに成功したらファイルに保存する
if (data) {
//ダウンロード成功
//ファイル名を決定する
//NSString *filePath = [self newFilePathWithURL:url];
//ローカルファイルへのURLを作成する
NSString *paths = [NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory,
NSUserDomainMask,
YES)lastObject];
paths = [paths stringByAppendingPathComponent:@"naisen.csv"];
NSLog(@"%@",paths);
//ファイルに保存する
isSuccessed = [data writeToFile:paths
options:NSDataWritingAtomic
error:&error];
}
else{
NSString *errMsg;
if (error) {
errMsg = [errMsg stringByAppendingString:[error localizedDescription]];
}
//エラーメッセージを表示する
UIAlertView *alert2;
alert2 = [[UIAlertView alloc]
initWithTitle:@"Error"
message:errMsg
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert2 show];
}
}
//新しいファイルへのファイルパスを取得する
- (NSString *)newFilePathWithURL:(NSURL *)url{
//URLからベースになっているファイル名を取得する
NSString *baseName = [[[url path]lastPathComponent]stringByDeletingPathExtension];
//ファイル名が取得出来なかったときは、固定の名前を使用する
if ([baseName length] == 0 || [baseName isEqual:@"/"]) {
baseName = @"newFile";
}
//拡張子を取得する
NSString *extension = [[url path]pathExtension];
//ドキュメントディレクトリのパスを取得する
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)lastObject];
//ループさせながらユニークなファイル名を決定する
NSFileManager *fileManager = [NSFileManager defaultManager];
NSInteger counter = 1;
NSString *newFilePath = nil;
while (1) {
@autoreleasepool {
//ファイルパスを作成する
NSString *tempFilePath;
if (counter == 1) {
//まずは連番を付けずに、元ファイルの名前をそのまま利用する
tempFilePath = [docDirPath stringByAppendingPathComponent:baseName];
}
else{
//元ファイルの名前に連番を追加する
tempFilePath = [NSString stringWithFormat:@"%@%ld",baseName,(long)counter];
tempFilePath = [docDirPath stringByAppendingPathComponent:tempFilePath];
}
//拡張子があれば追加する
if ([extension length] > 0) {
tempFilePath = [tempFilePath stringByAppendingPathExtension:extension];
}
//ファイルが存在するかチェックする
if (![fileManager fileExistsAtPath:tempFilePath]) {
break;
}
counter ++;
}
}
return newFilePath;
}
@end
そもそもこのソースで方向性は当っているのか、修正すれば正常に動作するのか?
現在、URLに直接ユーザネームとパスワードを打ち込んでいるのですが、それ以外の方法があるのか?
以上をすいませんがご教授お願いします。