需求
需要加載一個(gè)在線的 Web,通過 JSBridge
獲取到 Native 的資源路徑醒第,比如 file:///private/xxxx/xxx/xx.png
把它顯示在 WebView
當(dāng)中张惹。 舉個(gè)例子吧: 一個(gè) HTML
的 Image
標(biāo)簽想顯示iOS 沙盒里面的資源文件督暂。
<image src="file:///private/xxxx/xxx/xx.png"></image>
測試之后發(fā)現(xiàn)簡單寫本地路徑的路子走不通裳食。
查閱資料后發(fā)現(xiàn)通過 App 本地開啟 Server 服務(wù)哆姻,Root 開在沙盒目錄,然后通過將文件的 file協(xié)議
路徑轉(zhuǎn)換成本地服務(wù)路徑车遂,再給 H5 顯示封断,經(jīng)過測試完全可用。
第一步: 在 Podfile
寫入(關(guān)于 GCDWebServer舶担,一個(gè)輕量級(jí)的 AppServer 框架坡疼。)
pod "GCDWebServer", "~> 3.0"
pod install 集成后,在用到的地方
#import "GCDWebServer.h"
GCDWebServer*_webServer = [[GCDWebServer alloc] init];
[_webServer addGETHandlerForBasePath:@"/" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
[_webServer startWithPort:80 bonjourName:nil];
// 比方說文件存在Library下有一個(gè)123的文件
// NSString *basePath = @"http://localhost/Library/Caches/hxyhd/emeeting/imageurl.png"; // 這樣就可以訪問到這個(gè)文件了衣陶,我只需要把我的文件名拼上localhost路徑然后傳給前端柄瑰,他們拿到這個(gè)鏈接直接訪問就可以拿到這個(gè)文件了
然后在H5中需要加載資源的標(biāo)簽里 賦值完整地址如http://localhost/Library/Caches/hxyhd/emeeting/imageurl.png 就可以了
Caches/hxyhd/emeeting/imageurl.png
問題記錄
GCDWebServer不支持長鏈接,只要App退到后臺(tái)剪况,connect自動(dòng)就stop教沾,網(wǎng)頁請求無法獲得響應(yīng)。
解決辦法:
-1)開啟支持后臺(tái)模式:將GCDWebServer.m中的GCDWebServerOption_AutomaticallySuspendInBackground設(shè)置為NO译断;
-2)打開Background Modes授翻;
-3)在AppDelegate.m寫上這段代碼
-(void)applicationDidEnterBackground:(UIApplication *)application{
[[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:nil];;
}