检测新版本

这是一个非Appstore的更新检查,主要是根据后台的返回判断是否有版本更新,核心代码如下:

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
    [connection release];
    [receivedData release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
    
    NSString *result;
    result = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSString *content = [[result componentsSeparatedByString:@"<body>"] objectAtIndex:1];
    [result release];
    content = [[content componentsSeparatedByString:@"</body>"] objectAtIndex:0];
    content = [content stringByTrimmingCharactersInSet: [NSCharacterSet newlineCharacterSet]];
    
    [connection release];
    [receivedData release];
    
    if([content isEqualToString:@"Newest"] == YES) {
        newVersion = @"Newest";
    } else {
        newVersion = [[content componentsSeparatedByString:@"[New]"] objectAtIndex:0];
        newThings = [[content componentsSeparatedByString:@"[New]"] objectAtIndex:1];
        newThings = [content stringByTrimmingCharactersInSet: [NSCharacterSet newlineCharacterSet]];
    }
    [delegate checkFinishedWithNewVersion:newVersion NewThing:newThings];
}

- (void)cancelDownload {
    [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
    [theConncetion cancel];
    theConncetion = nil;
    receivedData = nil;
}

- (NSString *)getNowVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *result_ = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return result_;
}

- (void)checkNew {
    [self startCheckWithURLString:[NSString stringWithFormat:@"http://CheckUpdate.action?type=%@",[self getNowVersion]]];
}

- (void)startCheckWithURLString:(NSString *)theURL {
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL] cachePolicy:NSURLRequestUseProtocolCachePolicy  timeoutInterval:60.0];
    theConncetion = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if(theConncetion) {
        receivedData = [[NSMutableData data] retain];
        [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
    } else {
        NSLog(@"Can't start the connection!");
    }
}

猜你喜欢

转载自eric-gao.iteye.com/blog/1739879