使用ASIHTTPRequest来检查版本更新

- (void) alertWithTitle: (NSString *)_title_  msg:(NSString *)msg delegate:(id)_delegate cancelButtonTitle:(NSString*)_cancelTitle otherButtonTitles:(NSString*)_otherTitles{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_title_
                                                    message:msg
                                                   delegate:_delegate
                                          cancelButtonTitle:_cancelTitle
                                          otherButtonTitles:_otherTitles,nil];
    [alert show];
}

#pragma mark - update
-(void)checkUpdate{
    MBKAppDelegate *mbkApp = (MBKAppDelegate *)[[UIApplication sharedApplication] delegate];
    if (![mbkApp networkIsReach]) {
        return;
    }
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",kAppId]];
    ASIHTTPRequest *request =[ASIHTTPRequest requestWithURL:url];   
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)];
    [request startSynchronous];
}

#pragma mark - asihttprequest 
- (void)requestDone:(ASIHTTPRequest *)request
{
    NSError *err = nil;
    NSDictionary *dictionary =
    [[CJSONDeserializer deserializer] deserializeAsDictionary:[request responseData] error:&err];
    if (err != nil) {
        [self failure];
        return;
    }
    NSArray *a = [dictionary objectForKey:@"results"];
    if (a.count == 0) {
        [self failure];
        return;
    }
    NSDictionary *d = [a objectAtIndex:0];
    NSString *newVersion = [d objectForKey:@"version"];
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *nowVersion = [infoDict objectForKey:@"CFBundleVersion"];
    NSString *msg = @"";
    NSString *cancelTitle = @"";
    NSString *otherTitles = @"";
    if(![nowVersion isEqualToString:newVersion])
    {
        msg = @"版本有更新";
        cancelTitle = @"取消";
        otherTitles = @"更新";
    }else{        
        msg = @"已经是最新版本啦";
        cancelTitle = @"好";
        otherTitles = nil;
    }
    [self alertWithTitle:nil msg:msg delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:otherTitles];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/qun-xiang-dao/id%@?ls=1&mt=8",kAppId]];
        [[UIApplication sharedApplication]openURL:url];
    }
}

- (void)requestWentWrong:(ASIHTTPRequest *)request
{
    [self failure];
}

- (void)failure{    
    [self alertWithTitle:nil msg:@"检查失败了" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
}

你可能感兴趣的:(ASIHTTPRequest)