iOS NSURLSession下载

时间:2014-06-06 11:16:35

标签: ios nsurl

我得到了这段代码,可以帮助我从给定的URL下载文件。

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"Temporary File :%@\n", location);
    NSError *err = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSURL *docsDirURL = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:@"out1.zip"]];
    if ([fileManager moveItemAtURL:location
                             toURL:docsDirURL
                             error: &err])
    {
        NSLog(@"File is saved to =%@",docsDir);
    }
    else
    {
        NSLog(@"failed to move: %@",[err userInfo]);
    }

}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //You can get progress here
    NSLog(@"Received: %lld bytes (Downloaded: %lld bytes)  Expected: %lld bytes.\n",
          bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}

第二部分:

-(void) downloadFileWithProgress
{
    NSURL * url = [NSURL URLWithString:@"https://s3.amazonaws.com/hayageek/downloads/SimpleBackgroundFetch.zip"];
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDownloadTask * downloadTask =[ defaultSession downloadTaskWithURL:url];
    [downloadTask resume];

}

所有这些代码都在我的Download.m

我的download.h是:

@interface Download : NSObject
-(void) downloadFileWithProgress
@end

我真的不知道如何开始下载。在另一个课程中,我创建了一个应该开始下载的按钮:

-(IBAction)buttonStartDownload:(id)sender {
[Download downloadFileWithProgress];
}

错误位于最后一行:

No known class method for selector 'downloadFileWithProgress'

但为什么?

2 个答案:

答案 0 :(得分:1)

方法&#39 ;-(void)downloadFileWithProgress'是一种实例方法,因此您无法使用类名称'下载'来调用此方法。

要调用此方法,您需要创建一个'下载'的实例。 class并在该实例上调用该方法。

答案 1 :(得分:1)

Method -(void)downloadFilwWithProgress in instance method...So to call that method

-(IBAction)buttonStartDownload:(id)sender {
Download *downldObj=[[Download alloc]init];
[downldObj downloadFileWithProgress];
}


If you write method +(void)downloadFilwWithProgress then you can call like this.[Download downloadFileWithProgress]