2012-07-13 66 views
0

現在,當我的應用程序檢測到服務器上的文件已更新時,它會下載文件和用戶界面以阻止下載時間。我的應用程序中有ASIHTTPRequest包裝器,但我不知道如何將我的下載請求更改爲異步。如何使用異步請求下載文件?

我的代碼:

- (void)downloadFileIfUpdated 
{ 
    NSString *urlString = @"http://www.mysite.com/data.plist"; 
    NSLog(@"Downloading HTTP header from: %@", urlString); 
    NSURL *url = [NSURL URLWithString:urlString]; 

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *cachedPath = [[documentPaths lastObject] stringByAppendingPathComponent:@"data.plist"]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    BOOL downloadFromServer = NO; 

    NSString *lastModifiedString = nil; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"HEAD"]; 
    NSHTTPURLResponse *response; 
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL]; 
    if ([response respondsToSelector:@selector(allHeaderFields)]) { 
     lastModifiedString = [[response allHeaderFields] objectForKey:@"Last-Modified"]; 
    } 

    NSDate *lastModifiedServer = nil; 
    @try { 
     NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
     df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"; 
     df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
     df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
     lastModifiedServer = [df dateFromString:lastModifiedString]; 

    } 
    @catch (NSException * e) { 
    NSLog(@"Error parsing last modified date: %@ - %@", lastModifiedString, [e description]); 
    } 
    NSLog(@"lastModifiedServer: %@", lastModifiedServer); 

    NSDate *lastModifiedLocal = nil; 
    if ([fileManager fileExistsAtPath:cachedPath]) { 
     NSError *error = nil; 
     NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:cachedPath error:&error]; 
     if (error) { 
      NSLog(@"Error reading file attributes for: %@ - %@", cachedPath, [error localizedDescription]); 
     } 
     lastModifiedLocal = [fileAttributes fileModificationDate]; 
     NSLog(@"lastModifiedLocal : %@", lastModifiedLocal); 

     [activityIndicator stopAnimating]; 
    } 

    // Download file from server if we don't have a local file 
    if (!lastModifiedLocal) { 
     downloadFromServer = YES; 
    } 
    // Download file from server if the server modified timestamp is later than the local modified timestamp 
    if ([lastModifiedLocal laterDate:lastModifiedServer] == lastModifiedServer) { 


     [activityIndicator startAnimating]; 


     downloadFromServer = YES; 
    } 

    if (downloadFromServer) { 


     NSLog(@"Downloading new file from server"); 
     NSData *data = [NSData dataWithContentsOfURL:url]; 
     if (data) { 
      // Save the data 
      if ([data writeToFile:cachedPath atomically:YES]) { 
       NSLog(@"Downloaded file saved to: %@", cachedPath); 
      } 

      // Set the file modification date to the timestamp from the server 
      if (lastModifiedServer) { 
       NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:lastModifiedServer forKey:NSFileModificationDate]; 
       NSError *error = nil; 
       if ([fileManager setAttributes:fileAttributes ofItemAtPath:cachedPath error:&error]) { 
        NSLog(@"File modification date updated"); 
        [NSThread detachNewThreadSelector:@selector(loadPList) toTarget:self withObject:nil]; 

        [activityIndicator stopAnimating]; 



       } 
       if (error) { 
       NSLog(@"Error setting file attributes for: %@ - %@", cachedPath, [error localizedDescription]); 
       } 
      } 
     } 


    } 

} 
+0

什麼與蘋果文檔wromg http://developer.apple.com/library/ios/#DOCUMENTATION/ Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#// apple_ref/doc/uid/20001836-BAJEAIEE - 它提出了一種方法,並且在註釋的最後給出了sendSynchronousRequest並不推薦使用這種方法,因爲它有嚴格的限制 – Mark 2012-07-13 10:26:54

回答

1
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
[request setCompletionBlock:^{ 
    // Use when fetching text data 
    NSString *responseString = [request responseString]; 

    // Use when fetching binary data 
    NSData *responseData = [request responseData]; 
}]; 
[request setFailedBlock:^{ 
    NSError *error = [request error]; 
}]; 
[request startAsynchronous]; 

欲瞭解更多詳細看http://allseeing-i.com/ASIHTTPRequest/How-to-use#using_blocks

+0

是的,我看過這個例子..但不能mo dify我的代碼 – 2012-07-13 10:40:12

+0

在'if(downloadFromServer){...}'而不是你現在所做的事情中,放入來自示例的代碼。只需將URL替換爲您所需的。 – 2012-07-13 10:52:55

+0

好的..現在它可以工作......但它給了我一個ARC保留週期問題:在這個塊中強烈地捕獲'請求'很可能導致保留週期 – 2012-07-13 11:03:40