iOS GCDWebServer 搭建本地服務器
需求場景:H5 頁面 讀取系統(tǒng)相冊 ,把選中的圖片上傳給前端 H5. (H5不能直接讀取沙盒的路徑)
方案1:讀取到的二進制baseEncode 字符串形式交互
弊端:
-
安全性問題:JavaScript在瀏覽器中運行,可能存在潛在的安全風險,需要謹慎處理用戶照片,以免導致隱私泄露或安全問題。
-
性能問題:讀取大型圖片文件并轉換為數(shù)據(jù)URL可能影響頁面加載和響應速度,特別是處理大型圖片文件時會消耗較多的內存和時間。
-
瀏覽器兼容性:不同瀏覽器對文件API的支持程度有所不同,可能導致在某些瀏覽器上無法正常讀取或處理圖片文件。
-
移動設備限制:在移動設備上,尤其是iOS設備上,由于安全性限制和隱私保護,可能無法直接訪問系統(tǒng)相冊,限制了文件系統(tǒng)的訪問。
最主要就是這個性能問題,如果是多張圖片,圖片大小不可控,更會引起問題。
方案2:GCDWebServer 在 iOS 應用中創(chuàng)建本地服務器處理圖片上傳
優(yōu)點:
-
本地處理:能夠在 iOS 應用內部啟動本地服務器,允許直接從 H5 頁面上傳圖片到應用本地,便于應用內部的處理和管理。
-
靈活性:可以在服務器端對上傳的圖片數(shù)據(jù)進行必要的處理,如壓縮、裁剪、格式轉換等操作,以滿足應用特定的需求。
-
實時性:可通過本地服務器實現(xiàn)即時通信,快速響應上傳請求,加快圖片處理速度。
-
可定制性:GCDWebServer 提供了靈活的 API,允許開發(fā)者自定義路由和處理邏輯,以適應不同的業(yè)務場景。
潛在的缺點:
-
復雜性:對于不熟悉服務器端開發(fā)的開發(fā)者來說,使用 GCDWebServer 可能需要一定的學習成本,特別是對于涉及到網(wǎng)絡編程和服務器配置方面的知識。
-
維護成本:維護一個本地服務器需要考慮到安全補丁、更新、故障排查和性能優(yōu)化等方面,這可能需要較多的時間和精力。
-
性能問題:在處理大量或大型文件時,可能會對設備的性能產(chǎn)生一定的影響,尤其是在資源有限的設備上,可能導致性能下降或資源耗盡。
-
安全風險:開放一個本地服務器可能存在一些潛在的安全風險,例如未經(jīng)驗證的訪問、惡意請求和攻擊等問題,需要做好安全防護措施。
-
依賴性:應用依賴于第三方庫 GCDWebServer,如果該庫的更新不及時或存在 bug,可能會影響應用的穩(wěn)定性和功能。
-
網(wǎng)絡限制:本地服務器通常只能在局域網(wǎng)內使用,如果需要通過公網(wǎng)訪問,需要考慮網(wǎng)絡環(huán)境和配置公網(wǎng)訪問的安全性。
-
并發(fā)處理:GCDWebServer 默認采用 GCD(Grand Central Dispatch)進行請求的處理,如果處理大量并發(fā)請求,可能會對服務器性能產(chǎn)生影響,需要進行優(yōu)化。
鑒于,我們在局部功能使用,按需開啟服務,按需關閉服務,最終決定使用GCDWebServer。
使用舉例子
html 測試文件內容:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>展示圖片</title> </head> <body> <script> function showImage(base64) {//data base64 形式 var img = new Image(); img.src = "data:image/png;base64," + base64; img.style.width = "300px"; img.style.height = "200px"; document.body.appendChild(img); } function showImages1(imageStr) {//路由地址形式 var images = imageStr.split(","); for (var i = 0; i < images.length; i++) { var img = new Image(); img.src = "http://localhost:9999/Documents/KFZAlbumCameraRoot/" + images[i]; img.style.width = "300px"; img.style.height = "200px"; document.body.appendChild(img); } } </script> </body> </html>
pod 'GCDWebServer' #搭建本地服務器
創(chuàng)建管理類:
KFZGCDWebServer.h KFZGCDWebServer.m
#import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN ///本地服務器管理 @interface KFZGCDWebServer : NSObject - (void)startWebServer; - (void)stopWebServer; @end NS_ASSUME_NONNULL_END #import "KFZGCDWebServer.h" #import "GCDWebServer.h" @interface KFZGCDWebServer () <GCDWebServerDelegate> @property (nonatomic, strong) GCDWebServer *localServer; @end @implementation KFZGCDWebServer - (instancetype)init { self = [super init]; if (self) { } return self; } #pragma mark - event - (void)startWebServer { if (!self.localServer) { GCDWebServer *webServer = [[GCDWebServer alloc] init];
//這里最關鍵的是需要最后運行起來逐步調試 這個路由的路徑是否是你期望的路徑,容易多個/, 或者可能路徑重復了所以這里要特別注意 [webServer addGETHandlerForBasePath:@"/" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES]; self.localServer = webServer; } NSMutableDictionary* options = [NSMutableDictionary dictionary]; [options setObject:[NSNumber numberWithInteger:9999] forKey:GCDWebServerOption_Port]; // [options setValue:@"GCD Web Server" forKey:GCDWebServerOption_BonjourName];//??注意這里要用固定的端口號和bonjourName為nil,以成功繞過蘋果的本地網(wǎng)絡權限檢測 [options setValue:@(false) forKey:GCDWebServerOption_AutomaticallySuspendInBackground]; //??不主動掛起處理 // [self.localServer startWithOptions:options error:NULL]; } - (void)stopWebServer { [_localServer stop]; _localServer = nil; }
測試代碼:KFZTestHtmlVC.h KFZTestHtmlVC.m
@interface KFZTestHtmlVC () <KFZAlbumCameraDelegate> @property (nonatomic, strong) WKWebView *webView; @property (nonatomic, strong) KFZGCDWebServer *localWebServer; @end @implementation KFZTestHtmlVC - (void)viewDidLoad { [super viewDidLoad]; [self initWebServer]; [self addNavView]; [self configSubviews]; } - (void)dealloc { [_localWebServer stopWebServer]; // [KFZImageCacheManager clearCurrentImagePath:self.localIdentifier]; } #pragma mark - event - (void)rightButtonClick { [KFZAlbumCameraVC showPageFromVC:self maxPictureNum:120 defaultType:KFZAlbumCameraIndex_Camera isOnlyType:false isBlue:true callNextStepResult:^(NSArray * _Nonnull resultImages) { }]; } #pragma mark - KFZAlbumCameraDelegate /** 點擊下一步 圖片出口回執(zhí) */ - (void)handleCallNextStepResultImages:(NSArray * _Nullable )resultImages { DLog(@"%@",resultImages);
//這里回執(zhí)的是圖片相對路徑 eg "business1703064143/album1703064157/1703064185899.jpg" 然后在前端的 "http://localhost:9999/Documents/KFZAlbumCameraRoot/"拼成一個完整圖片地址就可以展示出來了
// 使用 JavaScript 將參數(shù)傳遞給 H5
NSString *script =[NSString stringWithFormat:@"showImages1('%@')",[resultImages componentsJoinedByString:@","]];
[self.webView evaluateJavaScript:script completionHandler:nil]; // server // [self.navigationController popViewControllerAnimated:true]; } - (void)initWebServer { self.localWebServer = [[KFZGCDWebServer alloc]init]; [self.localWebServer startWebServer]; } #pragma mark - private - (void)configSubviews { // webView [self.view addSubview:self.webView]; [self.webView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.bottom.right.equalTo(self.view); make.top.equalTo(self.stateNavBgView.mas_bottom); }]; [self loadWebRequest]; //documentPath NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; DLog(@"documentPath = %@",documentPath); } - (void)loadWebRequest { NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:request]; } - (void)addNavView { UIButton *rightButton = [[UIButton alloc] init]; UIColor *color = [UIColor kfz_colorTitle]; [rightButton setTitle:@"相機" forState:UIControlStateNormal]; [rightButton setTitleColor:color forState:UIControlStateNormal]; [rightButton.titleLabel setFont:[UIFont kfz_fontRegularSize:14]]; [rightButton addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside]; //右邊導航按鈕 [self.custemNavigation addSubview:rightButton]; [rightButton mas_makeConstraints:^(MASConstraintMaker *make) { make.right.mas_equalTo(0); make.centerY.equalTo(self.custemNavigation.mas_centerY); make.width.equalTo(@(80)); make.top.bottom.equalTo(@(0)); }]; } #pragma mark - getter setter - (WKWebView *)webView { if (!_webView) { _webView = [[WKWebView alloc]init]; } return _webView; } @end
圖片沙盒相對路徑 和 GCDWebServer 服務開啟的基地址進行拼接出來的
eg:
http://localhost:9999/Documents/KFZAlbumCameraRoot/business1703064143/album1703064157/1703064185899.jpg 就可以被H5 渲染到界面上了
效果圖 :

posted on 2023-12-20 17:33 ACM_Someone like you 閱讀(1412) 評論(0) 收藏 舉報
浙公網(wǎng)安備 33010602011771號