Recently I needed to automate the retrieval of the build number for the app I am currently developing, and instead of including the build number in a standard UI component like a UILabel, I needed to add it dynamically to some HTML that was being used as an About Us view.
The solution was pretty simple, but I thought I’d share it anyway since it was fun.
The first thing to do is edit the HTML, so at the place I needed to insert the build number, I simply added a rudimentary replaceable tag to the body of the HTML:
<p>Build: [BUILD_NUMBER]<p>
The next step was to add a method (though I could have also done this inline) to replace the tag with the build number, using [[[NSBundle mainBundle] infoDictionary] objectForKey:@”CFBundleVersion”] to retrieve the build number:
- (NSString *)insertBuildNumber:(NSString *)htmlContent {
NSString *buildNumber = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
htmlContent = [htmlContent stringByReplacingOccurrencesOfString:@"[BUILD_NUMBER]" withString:buildNumber];
return htmlContent;
}
Then, we put it all together in the method I was using to load the HTML. In this case I was just using ViewWillAppear.
- (void)viewWillAppear:(BOOL)animated {
// get the file path
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"about_us" ofType:@"html"];
// get the file content
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
// replace the tag with the build number
htmlString = [self insertBuildNumber:htmlString];
NSString *basePath = [[NSBundle mainBundle] bundlePath];
// load the HTML into the UIWebView
[self.webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:basePath]];
}
The final result worked great and now I can show the build number in the app as it gets updated via the Archive process (I have a separate script for that).