我得到了這段代碼來實現一些東西,可以幫助我從給定的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'
但是,爲什麼?
我們需要更多信息,您是否導入了您的下載幫助類?你爲什麼需要三個不同的課程? – mstottrop
好的,是的,我在「DownloadViewController.m」中導入了「Download.h」。將下載代碼外包給一個類並在downloadViewController類中引用它不是很有用嗎? – Velocity
我認爲現在只需在您的DownloadViewController類中擁有所有內容,因爲您只需外包單個函數即可。 – mstottrop