检查文件是否已在服务器上更新

时间:2013-11-20 21:09:15

标签: ios crash nsurlconnection

在我的应用程序和启动时,我检查服务器上的数据库是否已更改,并且本地存储了副本。我正在使用对服务器的同步请求,我正在根据HTTP响应中最后修改的日期时间字段进行检查

如果服务器上文件的最后修改数据时间是>本地文件的最后修改日期时间我询问用户是否要更新数据库,如果他接受我下载数据库。

我正在使用我的机器作为服务器但是当我关闭我的机器时问题,应用程序在启动时崩溃

谢谢你的帮助

您可以在下面找到我的代码

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController


- (void)viewDidLoad
{
    [super viewDidLoad];



    // check connectivity
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        [self displayConenctivityAlert];

    }else{

        [self checkDatabases];

    }



}




- (void) checkDatabases {


    bool res = [self fileUpdated];


    if (res){
        // Ask user if he would like to update the databases    
    }

}




-(void) displayConenctivityAlert{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[TSLanguageManager localizedString:@"NO_CONNECTED"] delegate:self cancelButtonTitle:[TSLanguageManager localizedString:@"OK"] otherButtonTitles:nil];

    [alert show];
}



- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Error HTTP ...");
}




- (BOOL)fileUpdated {
    NSString *urlString = @"http://192.168.0.10:8888/fuel/stations.db";
    NSLog(@"Downloading HTTP header from: %@", urlString);
    NSURL *url = [NSURL URLWithString:urlString];


    //store locally data into the resource folder.
    NSString *documentsDirectory = [Utility documentsPath];



    NSString *cachedPath = [documentsDirectory stringByAppendingPathComponent:@"stations.db"];
    NSLog(@"Local URL / %@", cachedPath);
    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);
    }

    // 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) {
        downloadFromServer = YES;
    }

    return downloadFromServer;
}

@end

2 个答案:

答案 0 :(得分:2)

你的应用程序崩溃了,因为完成didFinishLaunching系统看门狗杀死你的应用程序需要很长时间。这是因为您在根视图控制器的viewDidLoad中进行同步http请求,必须在完成启动之前完成。您可以通过多种方式解决此问题,通过调用NSURLConnection上的sendAsynchronousRequest:queue:completionHandler异步执行HTTP请求。另一种选择是将此代码移出启动管道,可能是将代码移动到视图控制器的viewDidAppear。这会产生副作用,即每次返回视图时都会检查,而不仅仅是初始加载。

简而言之,执行同步HTTP请求是一个很大的问题,因为您的UI将在请求完成之前挂起。在这种情况下,它特别糟糕,因为您迫使您的启动被延迟,直到请求完成,这导致它在服务器关闭时失败。

答案 1 :(得分:-1)

问题解决了

我现在正在使用

[NSURLConnection sendAsynchronousRequest:request    queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){


}

而不是

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];