.h
//
// myCheckUpdate.h
//
//
// Created by X on 13-9-25.
//
//
#import <Foundation/Foundation.h>
// 检查更新
@interface myCheckUpdate : NSObject <UIAlertViewDelegate, NSURLConnectionDelegate>
+(void) check;
@end
.m
//
// myCheckUpdate.m
//
//
// Created by X on 13-9-25.
//
//
#import "myCheckUpdate.h"
#import "CJSONDeserializer.h"
@implementation myCheckUpdate
// =============================================================
-(NSString*) getLocalVer {
NSDictionary* dict = [[NSBundle mainBundle] infoDictionary];
return [dict objectForKey:@"CFBundleVersion"];
}
#pragma mark-
#pragma mark- UIAlertViewDelegate
// =============================================================
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
// 弹出AppStore更新界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=yourAppID"]];
}
}
#pragma mark-
#pragma mark- NSURLConnectionDelegate
// =============================================================
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error{
// 当请求失败时的相关操作;
NSLog(@"Error info: %@", [error debugDescription]);
}
// 获取版本成功
// =============================================================
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data {
NSDictionary* dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:nil];
if (dict) {
NSArray* results = [dict objectForKey:@"results"];
if (results && results.count != 0) {
NSDictionary* resultsDict = [results objectAtIndex:0];
if (resultsDict) {
NSString* appstoreVer = [resultsDict objectForKey:@"version"];
if (appstoreVer && ![appstoreVer isEqualToString:[self getLocalVer]]) {
UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"检测到新版本,是否更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
[view show];
[view autorelease];
}
}
}
}
}
// =============================================================
-(void) start {
NSString* url = @"http://itunes.apple.com/cn/lookup?id=yourAppID";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:40] autorelease];
[request setHTTPMethod:@"GET"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
// =============================================================
+(void) check {
myCheckUpdate* checkInst = [[myCheckUpdate alloc] init];
[checkInst start];
}
@end
使用
[myCheckUpdate check];