2010-04-04 61 views
1

我想下載文件到下載文件夾。我搜索了谷歌,並找到了NSURLDownload類。我讀過的開發中心的頁面,並創造了這個代碼(有一些複製和粘貼)以下代碼:使用可可下載文件

@implementation Downloader 
@synthesize downloadResponse; 

- (void)startDownloadingURL:(NSString*)downloadUrl destenation:(NSString*)destenation { 
    // create the request 
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:downloadUrl] 
               cachePolicy:NSURLRequestUseProtocolCachePolicy 
              timeoutInterval:60.0]; 
    // create the connection with the request 
    // and start loading the data 
    NSURLDownload *theDownload=[[NSURLDownload alloc] initWithRequest:theRequest 
                   delegate:self]; 
    if (!theDownload) { 
     NSLog(@"Download could not be made..."); 
    } 
} 

- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename { 
    NSString *destinationFilename; 
    NSString *homeDirectory=NSHomeDirectory(); 

    destinationFilename=[[homeDirectory stringByAppendingPathComponent:@"Desktop"] 
         stringByAppendingPathComponent:filename]; 
    [download setDestination:destinationFilename allowOverwrite:NO]; 
} 

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error { 
    // release the connection 
    [download release]; 

    // inform the user 
    NSLog(@"Download failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo] objectForKey:NSErrorFailingURLStringKey]); 
} 

- (void)downloadDidFinish:(NSURLDownload *)download { 
    // release the connection 
    [download release]; 

    // do something with the data 
    NSLog(@"downloadDidFinish"); 
} 

- (void)setDownloadResponse:(NSURLResponse *)aDownloadResponse { 
    [aDownloadResponse retain]; 
    [downloadResponse release]; 
    downloadResponse = aDownloadResponse; 
} 

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response { 
    // reset the progress, this might be called multiple times 
    bytesReceived = 0; 

    // retain the response to use later 
    [self setDownloadResponse:response]; 
} 

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(unsigned)length { 
    long long expectedLength = [[self downloadResponse] expectedContentLength]; 

    bytesReceived = bytesReceived+length; 

    if (expectedLength != NSURLResponseUnknownLength) { 
     percentComplete = (bytesReceived/(float)expectedLength)*100.0; 
     NSLog(@"Percent - %f",percentComplete); 
    } else { 
     NSLog(@"Bytes received - %d",bytesReceived); 
    } 
} 

-(NSURLRequest *)download:(NSURLDownload *)download 
      willSendRequest:(NSURLRequest *)request 
     redirectResponse:(NSURLResponse *)redirectResponse { 
    NSURLRequest *newRequest=request; 
    if (redirectResponse) { 
     newRequest=nil; 
    } 
    return newRequest; 
} 
@end 

但我的問題是,現在,按規定它不顯示在桌面上。我想把它放在下載中,而不是放在桌面上... 我該怎麼做?

編輯: 最後一個堆:

#0 0x92169ed7 in objc_msgSend 
#1 0x01390090 in ?? 
#2 0x90443107 in URLDownload::didReceiveResponse 
#3 0x903ecfc0 in URLConnectionClient::_clientSendDidReceiveResponse 
#4 0x90465705 in URLConnectionClient::ClientConnectionEventQueue::processAllEventsAndConsumePayload 
#5 0x904658b2 in URLConnectionClient::ClientConnectionEventQueue::processAllEventsAndConsumePayload 
#6 0x903e0ace in URLConnectionClient::processEvents 
#7 0x903e096f in MultiplexerSource::perform 
#8 0x953df15b in __CFRunLoopDoSources0 
#9 0x953dcc1f in __CFRunLoopRun 
#10 0x953dc0f4 in CFRunLoopRunSpecific 
#11 0x953dbf21 in CFRunLoopRunInMode 
#12 0x96bc10fc in RunCurrentEventLoopInMode 
#13 0x96bc0eb1 in ReceiveNextEventCommon 
#14 0x96bc0d36 in BlockUntilNextEventMatchingListInMode 
#15 0x9775d135 in _DPSNextEvent 
#16 0x9775c976 in -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] 
#17 0x9771ebef in -[NSApplication run] 
#18 0x97716c85 in NSApplicationMain 
#19 0x00002628 in main at main.m:13 
+0

蘋果不鼓勵使用NSURLDownload並建議切換到NSURLSession - 看https://developer.apple.com/library/mac/documentation/Cocoa /Conceptual/URLLoadingSystem/URLLoadingSystem.html – pi3 2016-07-07 14:51:33

回答

3

你從來沒有使用過該目標字符串中-startDownloadingURL:destination:。想必你打電話給-[NSURLDownload setDestination:allowOverwrite:]

-[NSFileManager URLsForDirectory:NSDownloadsDirectory inDomains:NSUserDomainMask]應該讓你開始獲取下載目錄。我自己並不需要使用這種方法,我認爲文檔說,不能保證在方法返回時實際上有一個目錄。所以,你需要在這種情況下回退。

+0

我在代碼的另一部分發現了一個錯誤...現在我得到錯誤:'Downloader'可能不會響應'-alloc'。這是什麼意思?? – dododedodonl 2010-04-04 22:17:29

+0

聽起來好像你將alloc消息發送到你的下載器的實例而不是類。也許我不清楚,但是我把你的代碼添加到了 - [NSURLDownload setDestination:allowOverwrite:],並且它成功地下載了一個文件!我沒有看過其他錯誤(如泄漏)的代碼,但這應該讓你去。 – Ken 2010-04-04 22:30:21

+0

我寫了一個小寫字母D來代替大寫字母......另一個(小)問題:我如何調試一個'Program received signal:「EXC_BAD_ACCESS」'錯誤 – dododedodonl 2010-04-05 07:33:16

1
#0 0x92169ed7 in objc_msgSend 
#1 0x01390090 in ?? 
#2 0x90443107 in URLDownload::didReceiveResponse 

聽起來像是你沒有堅持自己的下載器,所以它死了,下載再發送一個委託消息已死的人下載的對象。

只要需要下載一些東西,請確保持有Downloader的東西。您可以使用Instruments的ObjectAlloc工具來跟蹤下載器的創建,保留和發佈,以查看您不應該執行哪些發佈。

不要忘記閱讀或重新閱讀the memory management docs(最近重寫),而你在這裏。

0

希望這會工作,它爲我工作:

-(void)createDownloadContentService:(NSURL *)url{ 
    NSLog(@"URL : %@",url); 
    NSString *tempFilePath = //Give directory path, make sure its exist and also give file name too, like /Desktop/downloading/filename.zip//; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:tempFilePath]) { 
      //Not needed if you dont want to resume// 
     NSURLDownload *download = [[NSURLDownload alloc] initWithResumeData:resumeData delegate:self path:tempFilePath]; 
     [download setDeletesFileUponFailure:NO]; 
     [download setDestination:tempFilePath allowOverwrite:YES]; 
    }else{ 
     NSURLDownload *download = [[NSURLDownload alloc] initWithRequest:[NSURLRequest requestWithURL:url] delegate:self]; 
     [download setDeletesFileUponFailure:NO]; 
     [download setDestination:tempFilePath allowOverwrite:YES]; 
    } 
} 



implement delegate----- 



- (void)downloadDidBegin:(NSURLDownload *)download{ 

} 



- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response{ 
    _totalLength = response.expectedContentLength; 
} 



- (void)download:(NSURLDownload *)download willResumeWithResponse:(NSURLResponse *)response fromByte:(long long)startingByte{ 

} 



- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length{ 
    _recievedLength = _recievedLength + length; 
} 



- (void)downloadDidFinish:(NSURLDownload *)download{ 
    // Completed, file will be available// 
} 



- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error{ 
    NSLog(@"FAILED DOWNLOAD: %@",[error localizedDescription]); 
}