2014-06-06 36 views
1

我得到了這段代碼來實現一些東西,可以幫助我從給定的URL下載文件。iOS NSURLSession下載

-(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' 

但是,爲什麼?

+0

我們需要更多信息,您是否導入了您的下載幫助類?你爲什麼需要三個不同的課程? – mstottrop

+0

好的,是的,我在「DownloadViewController.m」中導入了「Download.h」。將下載代碼外包給一個類並在downloadViewController類中引用它不是很有用嗎? – Velocity

+0

我認爲現在只需在您的DownloadViewController類中擁有所有內容,因爲您只需外包單個函數即可。 – mstottrop

回答

1

方法' - (void)downloadFileWithProgress'是一個實例方法,因此您無法使用類名'Download'調用此方法。

爲了調用這個方法,你需要創建一個'Download'類的實例並調用該實例的方法。

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] 
相關問題