Check For Available New App Version in Appstore

Note: Make sure that when you enter the new version in iTunes, this matches the version in the app you are releasing. If not then the above code will always return YES regardless if the user updates.

Objective-c

-(BOOL) needsUpdate{

NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];

NSString* appID = infoDictionary[@"CFBundleIdentifier"];

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@", appID]];

NSData* data = [NSData dataWithContentsOfURL:url];

NSDictionary* lookup = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

if ([lookup[@"resultCount"] integerValue] == 1){

NSString* appStoreVersion = lookup[@"results"][0][@"version"];

NSString* currentVersion = infoDictionary[@"CFBundleShortVersionString"];

if (![appStoreVersion isEqualToString:currentVersion]){

NSLog(@"Need to update [%@ != %@]", appStoreVersion, currentVersion);

return YES;

}

}

return NO;

}

Swift 3.0

func isUpdateAvailable() throws -> Bool {

guard let info = Bundle.main.infoDictionary,

let currentVersion = info["CFBundleShortVersionString"] as? String,

let identifier = info["CFBundleIdentifier"] as? String,

let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(identifier)") else {

throw VersionError.invalidBundleInfo

}

let data = try Data(contentsOf: url)

guard let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any] else {

throw VersionError.invalidResponse

}

if let result = (json["results"] as? [Any])?.first as? [String: Any], let version = result["version"] as? String {

return version != currentVersion

}

throw VersionError.invalidResponse

}

I think is better to throw an error instead of returning false, in this case I created a VersionError but it can be some other you define or NSError

enum VersionError: Error {

case invalidResponse, invalidBundleInfo

}

Also consider to call this function from another thread, if the connection is slow it can block the current thread.

DispatchQueue.global().async {

do {

let update = try self.isUpdateAvailable()

DispatchQueue.main.async {

// show alert

}

} catch {

print(error)

}

}

Reference

results matching ""

    No results matching ""