技术原理: 在iOS开发中可以使用openUrl的方式打开一个网页,并通过Safari浏览器的发送到主屏幕从而创建一个网页的快捷方式,这篇文章就是利用这个方法来创建一个app的桌面快捷方式。首先在app内部开启一个轻量级的HttpServer,利用openurl:127.0.0.1 的方式打开本地页面,利用html的重定向将页面指向一个包含创建桌面快捷方式所有信息的,遵守data协议的url,这时利用Safari的发送到主屏幕,就可以达到我们的要求。
技术难点:
1. 创建一个本地的httpServer。2. 创建本地页面以及data协议url时的编码格式。3. 在Safari未启动时或者app进入后台时,本地httpserver服务启动延迟。
/*
*添加至桌面快捷方式,创建一个本地站点
*/
- (IBAction)addDesktopShortCut:(id)sender {
[selfcreateHtml];
ITER_MAP_STR_SCENEiterScene =m_map_id_str_scene[mStrGatewayID].find(mStrSceneID);
NSDictionary*pramasDic = [SceneShortcutGetSceneShortcutParameters:mStrGatewayIDsceneIterate:iterScene];
if(pramasDic) {
[selfcreateLinkWithDict:pramasDicdesktopLinkType:SyDesktopLinkType_One];
}
}
//创建HTMl
- (void)createHtml {
//启动本地httpSever和服务器首页页面
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documentsPath = paths[0];
self.webRootDir= [documentsPathstringByAppendingPathComponent:@"web"];
BOOLisDirectory =YES;
BOOLexsit = [[NSFileManagerdefaultManager]fileExistsAtPath:_webRootDirisDirectory:&isDirectory];
if(!exsit){
[[NSFileManagerdefaultManager]createDirectoryAtPath:_webRootDirwithIntermediateDirectories:YESattributes:nilerror:nil];
}
self.mainPage= [NSStringstringWithFormat:@"%@/web/index.html",documentsPath];
[DDLogaddLogger:[DDTTYLoggersharedInstance]];
_httpServer= [[HTTPServeralloc]init];
[_httpServersetType:@"_http._tcp."];
[_httpServersetDocumentRoot:_webRootDir];
NSError*error;
if([_httpServerstart:&error])
{
DDLogInfo(@"Started HTTP Server on port %hu", [_httpServerlisteningPort]);
}
else
{
DDLogError(@"Error starting HTTP Server: %@", error);
}
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(applicationDidEnterBackground:)name:UIApplicationDidEnterBackgroundNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(applicationWillEnterForeground:)name:UIApplicationWillEnterForegroundNotificationobject:nil];
}
- (void)applicationDidEnterBackground:(UIApplication*)application
{
if([[UIDevicecurrentDevice].systemVersionintegerValue] >=6.0){
sleep(1);
}else{
sleep(2);
}
[_httpServerstop];
}
- (void)applicationWillEnterForeground:(UIApplication*)application
{
NSError*error;
if(![_httpServerisRunning]){
if([_httpServerstart:&error])
{
DDLogInfo(@"Started HTTP Server on port %hu", [_httpServerlisteningPort]);
}
else
{
DDLogError(@"Error starting HTTP Server: %@", error);
}
}
}
- (void)createLinkWithDict:(NSDictionary*)dict desktopLinkType:(SyDesktopLinkType)linkType {
NSString*imageUrlStr = [NSStringstringWithFormat:@"if (window.navigator.standalone == true) {var lnk = document.getElementById(\"qbt\");var evt = document.createEvent('MouseEvent');evt.initMouseEvent('click');lnk.dispatchEvent(evt);}else{var addObj=document.createElement(\"link\");addObj.setAttribute('rel','apple-touch-icon-precomposed');addObj.setAttribute('href','data:image/png;base64,%@');",base6ImageStr];
NSString*lastHtmlStr =@"document.getElementsByTagName(\"head\")[0].appendChild(addObj);document.getElementById(\"msg\").innerHTML='
[taragerUrlappendString:htmlUrlScheme];
[taragerUrlappendString:dataUrlStr];
// NSString转UTF8
NSString*dataUrlEncode = [selfurlUTF8Encoded:taragerUrl];
NSString*imageUrlEncode = [selfurlUTF8Encoded:imageUrlStr];
NSString*lastHtmlStrEncode = [selfurlUTF8Encoded:lastHtmlStr];
[htmlStrappendFormat:@"",dataUrlEncode,imageUrlEncode,lastHtmlStrEncode];
[htmlStrappendString:@""];
NSData*data = [htmlStrdataUsingEncoding:NSUTF8StringEncoding];
[datawriteToFile:_mainPageatomically:YES];
NSString*urlStrWithPort = [NSStringstringWithFormat:@"http://127.0.0.1:%d",[_httpServerlisteningPort]];
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:urlStrWithPort]];
}
//NSString转UTF8
-(NSString*)urlUTF8Encoded:(NSString*)urlString {
NSString* encodedString = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8));
//NSURL *url =[NSURL URLWithString:encodedString];
returnencodedString;
//解决乱码问题()
//NSString *transString = [NSString stringWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}