2016年1月12日 星期二

iOS筆記:NSURLSession for ftp requests (3): download

下載篇。
很遺憾的是上載的方法在文檔中標示了只支援HTTP request。



照慣例先弄出個HTTP下載的code,把url改成ftp網址。
(這樣就好了?沒錯!)

- (void)downloadTask
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"ftp://account:password@192.168.0.1/image.jpg"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        //app內Documents的路徑
        NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        //response.suggestedFilename: 下載目標的檔案名稱(image.jpg)
        NSString *file = [document stringByAppendingPathComponent:response.suggestedFilename];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //從下載暫存區(tmp)移動至Documents
        [fileManager moveItemAtPath:location.path toPath:file error:nil];
        NSLog(@"[DownloadTask]success!");
        
    }];
    [downloadTask resume];
}


下載完成後會把檔案放在tmp/,檔案名稱大約是這樣子的東西:CFNetworkDownload_KUd5ZI.tmp
在block內的動作就是把載來的檔案移到Documents,連帶檔名改成跟ftp抓下來的檔案名稱一樣。

沒有留言:

張貼留言