使用Swift将文件下载到根应用程序目录中

时间:2014-08-29 21:46:42

标签: ios swift nsurlsession

我是Swift编码的新手,我对Objective C的经验不多,所以我试图从网上下载一个文件(csv)并将其转储到根程序目录中。

不幸的是,我在Swift中找不到任何操作指南,尽管我正在编写ObjectiveC中的http://www.appcoda.com/background-transfer-service-ios7/教程。

这可能是非常基本的(并且道歉)但我正在尝试在Swift中创建一个类来替换ObjectiveC中的FileDownloadInfo类的实现。 (如果有人有教程的Swift示例,那将非常有帮助。

ObjectiveC中的实施是:

@implementation FileDownloadInfo

-(id)initWithFileTitle:(NSString *)title andDownloadSource:(NSString *)source{
    if (self == [super init]) {
        self.fileTitle = title;
        self.downloadSource = source;
        self.downloadProgress = 0.0;
        self.isDownloading = NO;
        self.downloadComplete = NO;
        self.taskIdentifier = -1;
    }

    return self;
}

@end

然后通过

填充FileDownloadArray
-(void)initializeFileDownloadDataArray{
    self.arrFileDownloadData = [[NSMutableArray alloc] init];

    [self.arrFileDownloadData addObject:[[FileDownloadInfo alloc] initWithFileTitle:@"iOS Programming Guide" andDownloadSource:@"https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf"]];
}

我在Swift类中创建了以下内容,但当然没有函数 - 如何修改它以使我能够以与上面相同的方式填充数组?

import UIKit

class FileDownloadInfo: NSObject {

    var fileTitle: NSString
    var downloadSource: NSString
    var downloadTask: NSURLSessionDownloadTask?
    var taskResumeData: NSData?
    var downloadProgress: Double
    var isDownloading: Bool
    var downloadComplete: Bool
    var taskIdentifier: Int

init(initWithFileTitle title: NSString, andDownloadSource source: NSString) {
        self.fileTitle = title
        self.downloadSource = source
        self.downloadProgress = 0.0
        self.isDownloading = false
        self.downloadComplete = false
        self.taskIdentifier = -1
}


}

1 个答案:

答案 0 :(得分:0)

我只阅读了部分介绍,这是我对它的看法。希望它可以提供帮助。为了直接翻译,您可以尝试:

func initializeFileDownloadDataArray(){
    arrFileDownloadData = [FileDownloadInfo]()
    arrFileDownloadData.append(FileDownloadInfo("iOS Programming Guide", downloadSource:"https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf" ))
}

如果我正确阅读,初始化程序的格式如下:

init(title: String, downloadSource: String) {
    self.fileTitle = title
    self.downloadSource = source
    self.downloadProgress = 0.0
    self.isDownloading = false
    self.downloadComplete = false
    self.taskIdentifier = -1
}

希望这有效。