技術(shù)原理: 在iOS開發(fā)中可以使用openUrl的方式打開一個網(wǎng)頁拍棕,并通過Safari瀏覽器的發(fā)送到主屏幕從而創(chuàng)建一個網(wǎng)頁的快捷方式,這篇文章就是利用這個方法來創(chuàng)建一個app的桌面快捷方式。首先在app內(nèi)部開啟一個輕量級的HttpServer,利用openurl:127.0.0.1 的方式打開本地頁面喜德,利用html的重定向?qū)㈨撁嬷赶蛞粋€包含創(chuàng)建桌面快捷方式所有信息的,遵守data協(xié)議的url垮媒,這時(shí)利用Safari的發(fā)送到主屏幕舍悯,就可以達(dá)到我們的要求。
技術(shù)難點(diǎn):
1. 創(chuàng)建一個本地的httpServer睡雇。2. 創(chuàng)建本地頁面以及data協(xié)議url時(shí)的編碼格式萌衬。3. 在Safari未啟動時(shí)或者app進(jìn)入后臺時(shí),本地httpserver服務(wù)啟動延遲它抱。
/*
*添加至桌面快捷方式秕豫,創(chuàng)建一個本地站點(diǎn)
*/
- (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];
}
}
//創(chuàng)建HTMl
- (void)createHtml {
//啟動本地httpSever和服務(wù)器首頁頁面
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轉(zhuǎn)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轉(zhuǎn)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]];
}