iOS用WKWebView与JS交互获取系统图片及WKWebView的Alert,Confirm,TextInput的监听代理方法使用,屏蔽WebView的可选菜单

http://blog.csdn.net/boyqicheng/article/details/52812968

最近做一个项目,开始是使用WebView与JS交互的,由于内存管理方面WebView欠佳。WKWebVIew的内存线程管理好,所以选择使用 WKWebVIew(使用WKWebView 的缺点在于,这个控件加载的H5页面不支持ajax请求,所以需要自己把网络请求在OC上实现)。

一、首先说下应该注意的问题:

1.要获取拍照或相册的图片,如果是iOS 10系统,需要设置访问权限(在 Info-plist 中设置)

相机权限: Privacy - Camera Usage Description 是否允许此App使用你的相机?
相册权限: Privacy - Photo Library Usage Description 是否允许此App访问你的媒体资料库?

2.WebView和WKWebView和JS互调的方法和使用的传参类型不同

WebView 使用 (window.iosModel.getImage(JSON.stringify(parameter)); //JSON.stringify(参数字符串) 这个方法是 把字符串转换成json字符串 parameter是参数字符串
   )传值给 OC

WKWebView 使用 (window.webkit.messageHandlers.iosModel.postMessage(parameter))

3.需要特别注意的是:WKWebView 不执行JS写的 ajax请求(WKWebView 可能由于基于 WebKit,并不会执行 C socket 相关的函数对 HTTP 请求进行处理)如果有网络请求,需要自己用OC实现

4.使用的时候不要忘记挂上使用到的代理,和导入代理

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @interface ViewController () <WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>  

5.屏蔽WebView的可选菜单(即不会出现拷贝、全选等弹出菜单)在加载完成后的代理中执行以下两段JS

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 导航完成时,会回调(也就是页面载入完成了)  
  2. - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {  
  3.     NSLog(@"66===%s", __FUNCTION__);  
  4.     // 禁用选中效果  
  5.     [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];  
  6.     [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];  
  7. }  




二、代码:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="UTF-8">  
  5.         <title></title>  
  6.     </head>  
  7.     <body>  
  8.         <div>  
  9.             <h3>JS与iOS交互</h3>  
  10.             <h4>JS页面获取iOS系统图片</h5>  
  11.         </div>  
  12.         <div>  
  13.             <input type = "button" style="width: 50%;height: 5%;" id="Button" value="打开相机获取图片" onclick="getIOSImage()"></button>  
  14.         </div><dir />  
  15.         <div>  
  16.             <img src="testImage.png" id="changeImage"style="width: 30%; height: 30%;" onclick="getIOSImage()"><!--src="图片的相对路径" 如果把html文件导入工程中,图片路径和OC一样只写图片名字和后缀就可以,(记得要先把图片添加到工程) 图片也可以实现按钮的方法getIOSImage -->  
  17.         </div>  
  18.         <span id="iosParame" style="width: 200px; height: 50%; color:orangered; font-size:15px" value="等待获取ios参数" >  
  19.             </div>  
  20.         <script>  
  21.             var getIOSImage = function(){  
  22.                 var parameter = {'title':'JS调OC','describe':'这里就是JS传给OC的参数'};  
  23.                 // 在下面这里实现js 调用系统原生api iosDelegate  
  24.                 //JSON.stringify(参数字符串) 这个方法是 把字符串转换成json字符串  
  25.     window.iosDelegate.getImage(JSON.stringify(parameter));// 实现数据的 json 格式字符串  
  26.             }  
  27.         // 这里是 iOS调用js的方法  
  28.         function setImageWithPath(arguments){  
  29.             document.getElementById('changeImage').src = arguments['imagePath'];  
  30.             document.getElementById('iosParame').innerHTML = arguments['iosContent'];  
  31.         }  
  32.         </script>  
  33.     </body>  
  34. </html>  

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <pre name="code" class="objc">#import "ViewController.h"  
  2. #import <JavaScriptCore/JavaScriptCore.h>  
  3. #import <WebKit/WebKit.h>  
  4. #import "SaveImage_Util.h"  
  5.   
  6. @interface ViewController () <WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>  
  7.   
  8. @property (nonatomicstrongWKWebView *webView;  
  9. @property (nonatomicstrongUIProgressView *progressView;  
  10.   
  11. @end  
  12.   
  13. @implementation ViewController  
  14. {  
  15.     int indextNumb;// 交替图片名字  
  16.     UIImage *getImage;//获取的图片  
  17. }  
  18. - (void)viewDidLoad {  
  19.   [super viewDidLoad];  
  20.     
  21.   self.edgesForExtendedLayout = UIRectEdgeNone;  
  22.   self.automaticallyAdjustsScrollViewInsets = NO;  
  23.     
  24.   WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];  
  25.   // 设置偏好设置  
  26.   config.preferences = [[WKPreferences alloc] init];  
  27.   // 默认为0  
  28.   config.preferences.minimumFontSize = 10;  
  29.   // 默认认为YES  
  30.   config.preferences.javaScriptEnabled = YES;  
  31.   // 在iOS上默认为NO,表示不能自动通过窗口打开  
  32.   config.preferences.javaScriptCanOpenWindowsAutomatically = NO;  
  33.   
  34.   
  35.   // web内容处理池  
  36.   config.processPool = [[WKProcessPool alloc] init];  
  37.   
  38.   // 通过JS与webview内容交互  
  39.   config.userContentController = [[WKUserContentController alloc] init];  
  40.   // 注入JS对象名称AppModel,当JS通过AppModel来调用时,  
  41.   // 我们可以在WKScriptMessageHandler代理中接收到  
  42.   [config.userContentController addScriptMessageHandler:self name:@"iosModel"];  
  43.   
  44.   
  45.   
  46.         //通过默认的构造器来创建对象  
  47.   self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];  
  48.     // 导航代理  
  49.     self.webView.navigationDelegate = self;  
  50.     // 与webview UI交互代理  
  51.     self.webView.UIDelegate = self;  
  52.   NSURL *path = [[NSBundle mainBundle] URLForResource:@"testJS" withExtension:@"html"];  
  53.   [self.webView loadRequest:[NSURLRequest requestWithURL:path]];  
  54.   [self.view addSubview:self.webView];  
  55.     
  56.     
  57.   
  58.   // 添加KVO监听  
  59.   [self.webView addObserver:self  
  60.                  forKeyPath:@"loading"  
  61.                     options:NSKeyValueObservingOptionNew  
  62.                     context:nil];  
  63.   [self.webView addObserver:self  
  64.                  forKeyPath:@"title"  
  65.                     options:NSKeyValueObservingOptionNew  
  66.                     context:nil];  
  67.   [self.webView addObserver:self  
  68.                  forKeyPath:@"estimatedProgress"  
  69.                     options:NSKeyValueObservingOptionNew  
  70.                     context:nil];  
  71.   
  72.   // 添加进入条  
  73.   self.progressView = [[UIProgressView alloc] init];  
  74.   self.progressView.frame = self.view.bounds;  
  75.   [self.view addSubview:self.progressView];  
  76.   self.progressView.backgroundColor = [UIColor blackColor];  
  77.     
  78.   self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"后退" style:UIBarButtonItemStyleDone target:self action:@selector(goback)];  
  79.   self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"前进" style:UIBarButtonItemStyleDone target:self action:@selector(gofarward)];  
  80. }  
  81.   
  82. - (void)goback {  
  83.   if ([self.webView canGoBack]) {  
  84.     [self.webView goBack];  
  85.   }  
  86. }  
  87.   
  88. - (void)gofarward {  
  89.   if ([self.webView canGoForward]) {  
  90.     [self.webView goForward];  
  91.   }  
  92. }  
  93.   
  94. #pragma mark - WKScriptMessageHandler  
  95. // 通过这个方法获取 JS传来的json字符串  
  96. - (void)userContentController:(WKUserContentController *)userContentController  
  97.       didReceiveScriptMessage:(WKScriptMessage *)message  
  98. {  
  99.   if ([message.name isEqualToString:@"iosModel"]) {  
  100.     // 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,  
  101.     // NSDictionary, and NSNull类型  
  102.       NSLog(@"JS传来的json字符串 :  %@", message.body);  
  103.       NSDictionary *jsDictionary = message.body;  
  104.       if ([jsDictionary[@"means"] isEqualToString:@"获取系统图片"])  
  105.       {  
  106.           [self beginOpenPhoto];  
  107.       }  
  108.   }  
  109. }  
  110.   
  111. #pragma mark - KVO  
  112. - (void)observeValueForKeyPath:(NSString *)keyPath  
  113.                       ofObject:(id)object  
  114.                         change:(NSDictionary<NSString *,id> *)change  
  115.                        context:(voidvoid *)context {  
  116.   if ([keyPath isEqualToString:@"loading"]) {  
  117.     NSLog(@"loading");  
  118.   } else if ([keyPath isEqualToString:@"title"]) {  
  119.     self.title = self.webView.title;  
  120.   } else if ([keyPath isEqualToString:@"estimatedProgress"]) {  
  121.     NSLog(@"progress: %f"self.webView.estimatedProgress);  
  122.     self.progressView.progress = self.webView.estimatedProgress;  
  123.   }  
  124.   if (!self.webView.loading) {  
  125.     [UIView animateWithDuration:0.5 animations:^{  
  126.       self.progressView.alpha = 0;  
  127.     }];  
  128.   }  
  129. }  
  130.   
  131. #pragma mark - WKNavigationDelegate  
  132.     // 请求开始前,会先调用此代理方法  
  133.     // 与UIWebView的  
  134.     // - (BOOL)webView:(UIWebView *)webView  
  135.     // shouldStartLoadWithRequest:(NSURLRequest *)request  
  136.     // navigationType:(UIWebViewNavigationType)navigationType;  
  137.     // 类型,在请求先判断能不能跳转(请求)  
  138.   
  139. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:  
  140. (WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {  
  141.   NSString *hostname = navigationAction.request.URL.host.lowercaseString;  
  142.   if (navigationAction.navigationType == WKNavigationTypeLinkActivated  
  143.       && ![hostname containsString:@".lanou.com"]) {  
  144. // 对于跨域,需要手动跳转, 用系统浏览器(Safari)打开  
  145.     [[UIApplication sharedApplication] openURL:navigationAction.request.URL];  
  146.       
  147.     // 不允许web内跳转  
  148.     decisionHandler(WKNavigationActionPolicyCancel);  
  149.   } else {  
  150.     self.progressView.alpha = 1.0;  
  151.     decisionHandler(WKNavigationActionPolicyAllow);  
  152.   }  
  153.     
  154. }  
  155.   
  156.   
  157.     // 在响应完成时,会回调此方法  
  158.     // 如果设置为不允许响应,web内容就不会传过来  
  159. - (void)webView:(WKWebView *)webView  
  160. decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse  
  161. decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {  
  162.   decisionHandler(WKNavigationResponsePolicyAllow);  
  163.     
  164. }  
  165.   
  166.   
  167. // 开始导航跳转时会回调  
  168. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {  
  169.      
  170. }  
  171.   
  172.     // 接收到重定向时会回调  
  173. - (void)webView:(WKWebView *)webView  
  174. didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {  
  175.      
  176. }  
  177.   
  178.   
  179.     // 导航失败时会回调  
  180. - (void)webView:(WKWebView *)webView  
  181. didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {  
  182.       
  183. }  
  184.   
  185.   
  186. // 页面内容到达main frame时回调  
  187. - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {  
  188.       
  189. }  
  190.   
  191. // 导航完成时,会回调(也就是页面载入完成了)  
  192. - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {  
  193.     NSLog(@"66===%s", __FUNCTION__);  
  194.     // 禁用选中效果  
  195.     [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];  
  196.     [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];  
  197. }  
  198.     // 导航失败时会回调  
  199. - (void)webView:(WKWebView *)webView didFailNavigation:  
  200. (null_unspecified WKNavigation *)navigation withError:(NSError *)error  
  201. {  
  202.       
  203. }  
  204.   
  205.   
  206. /* 对于HTTPS的都会触发此代理,如果不要求验证,传默认就行 
  207.     如果需要证书验证,与使用AFN进行HTTPS证书验证是一样的 */  
  208.   
  209. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:  
  210. (NSURLAuthenticationChallenge *)challenge completionHandler:  
  211. (void (^)(NSURLSessionAuthChallengeDisposition disposition,  
  212.           NSURLCredential *__nullable credential))completionHandler  
  213. {  
  214.   completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);  
  215. }  
  216.   
  217.   
  218. // 9.0才能使用,web内容处理中断时会触发  
  219. /* 
  220. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { 
  221. } 
  222. */  
  223. #pragma mark - WKUIDelegate  
  224. - (void)webViewDidClose:(WKWebView *)webView {  
  225.       
  226. }  
  227. /* 在JS端调用alert函数时,会触发此代理方法。JS端调用alert时所传的数据可以通过message拿到 在原生得到结果后,需要回调JS,是通过completionHandler回调 */  
  228. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message  
  229. initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler  
  230. {  
  231.   UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:message preferredStyle:UIAlertControllerStyleAlert];  
  232.   [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {  
  233.     completionHandler();  
  234.   }]];  
  235.     
  236.   [self presentViewController:alert animated:YES completion:NULL];  
  237.   NSLog(@"%@", message);  
  238.    
  239. }  
  240.   
  241.     // JS端调用confirm函数时,会触发此方法  
  242.     // 通过message可以拿到JS端所传的数据  
  243.     // 在iOS端显示原生alert得到YES/NO后  
  244.     // 通过completionHandler回调给JS端  
  245. - (void)webView:(WKWebView *)webView  
  246. runJavaScriptConfirmPanelWithMessage:(NSString *)message  
  247. initiatedByFrame:(WKFrameInfo *)frame  
  248. completionHandler:(void (^)(BOOL result))completionHandler {  
  249.   UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:message preferredStyle:UIAlertControllerStyleAlert];  
  250.   [alert addAction:[UIAlertAction actionWithTitle:@"确定"  
  251.     style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){  
  252.     completionHandler(YES);  
  253.   }]];  
  254.   [alert addAction:[UIAlertAction actionWithTitle:@"取消"  
  255.   style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action)  
  256.     {  
  257.     completionHandler(NO);  
  258.   }]];  
  259.   [self presentViewController:alert animated:YES completion:NULL];  
  260.   NSLog(@"%@", message);  
  261. }  
  262.  // JS端调用prompt函数时,会触发此方法  
  263.     // 要求输入一段文本  
  264.     // 在原生输入得到文本内容后,通过completionHandler回调给JS  
  265. - (void)webView:(WKWebView *)webView  
  266. runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt  
  267.     defaultText:(nullable NSString *)defaultText  
  268. initiatedByFrame:(WKFrameInfo *)frame  
  269. completionHandler:(void (^)(NSString * __nullable result))completionHandler  
  270. {  
  271.   UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert];  
  272.   [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {  
  273.     textField.textColor = [UIColor redColor];  
  274.   }];  
  275.   [alert addAction:[UIAlertAction actionWithTitle:@"确定"  
  276.     style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {  
  277.     completionHandler([[alert.textFields lastObject] text]);  
  278.   }]];  
  279.     
  280.   [self presentViewController:alert animated:YES completion:NULL];  
  281. }  
  282.   
  283. //  获取图片  
  284. - (void)beginOpenPhoto  
  285. {  
  286.     // 主队列 异步打开相机  
  287.     dispatch_async(dispatch_get_main_queue(), ^{  
  288.         [self takePhoto];  
  289.     });  
  290. }  
  291. #pragma mark 取消选择照片代理方法  
  292. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker  
  293. {  
  294.     [picker dismissViewControllerAnimated:YES completion:nil];  
  295. }  
  296. #pragma mark      //打开本地照片  
  297. - (void) localPhoto  
  298. {  
  299.     UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];  
  300.     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;  
  301.     imagePicker.delegate = self;  
  302.     [self presentViewController:imagePicker animated:YES completion:nil];  
  303. }  
  304. #pragma mark      //打开相机拍照  
  305. - (void) takePhoto  
  306. {  
  307.     UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;  
  308.     if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])  
  309.     {  
  310.         UIImagePickerController *picker = [[UIImagePickerController alloc]init];  
  311.         picker.delegate = self;  
  312.         picker.allowsEditing = YES;  
  313.         picker.sourceType = sourceType;  
  314.         picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;  
  315.         [self presentViewController:picker animated:YES completion:nil];  
  316.     }  
  317.     else  
  318.     {  
  319.         NSLog(@"模拟器中不能打开相机");  
  320.         [self localPhoto];  
  321.     }  
  322. }  
  323. //  选择一张照片后进入这里  
  324. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info  
  325. {  
  326.     NSString *type = [info objectForKey:UIImagePickerControllerMediaType];  
  327.     //  当前选择的类型是照片  
  328.     if ([type isEqualToString:@"public.image"])  
  329.     {  
  330.         // 获取照片  
  331.         getImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];  
  332.         NSLog(@"===Decoded image size: %@", NSStringFromCGSize(getImage.size));  
  333.         // obtainImage 压缩图片 返回原尺寸  
  334.         indextNumb = indextNumb == 1?2:1;  
  335.         NSString *nameStr = [NSString stringWithFormat:@"Varify%d.jpg",indextNumb];  
  336.         [SaveImage_Util saveImage:getImage ImageName:nameStr back:^(NSString *imagePath) {  
  337.             dispatch_async(dispatch_get_main_queue(), ^{  
  338.                 NSLog(@"图片路径:%@",imagePath);  
  339.                 /** 
  340.                  *  这里是IOS 调 js 其中 setImageWithPath 就是js中的方法 setImageWithPath(),参数是字典 
  341.                  */  
  342.                 NSString *callJSString = [NSString stringWithFormat:@"%@({\"imagePath\":\"%@\",\"iosContent\":\"获取图片成功,把系统获取的图片路径传给js 让html显示\"})",@"setImageWithPath",imagePath];  
  343.                 [self.webView evaluateJavaScript:callJSString completionHandler:^(id resultObject, NSError * _Nullable error) {  
  344.                     if (!error)  
  345.                     {  
  346.                         NSLog(@"OC调 JS成功");  
  347.                     }  
  348.                     else  
  349.                     {  
  350.                         NSLog(@"OC调 JS 失败");  
  351.                     }  
  352.                 }];  
  353.             });  
  354.         }];  
  355.         [picker dismissViewControllerAnimated:YES completion:nil];  
  356.     }  
  357. }  
  358.   
  359. @end  




 
下面是图片处理的 工具类 

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //  SaveImage_Util.h  
  2. //  JS和iOS交互  
  3. //  
  4. //  Created by user on 16/10/14.  
  5. //  Copyright © 2016年 user. All rights reserved.  
  6. //  
  7.   
  8. #import <Foundation/Foundation.h>  
  9. #import <UIKit/UIKit.h>  
  10. @interface SaveImage_Util : NSObject  
  11. #pragma mark  保存图片到document  
  12. + (BOOL)saveImage:(UIImage *)saveImage ImageName:(NSString *)imageName back:(void(^)(NSString *imagePath))back;  
  13.   
  14. @end  

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //  SaveImage_Util.m  
  2. //  JS和iOS交互  
  3. //  
  4. //  Created by user on 16/10/14.  
  5. //  Copyright © 2016年 user. All rights reserved.  
  6. //  
  7.   
  8. #import "SaveImage_Util.h"  
  9.   
  10. @implementation SaveImage_Util  
  11. #pragma mark  保存图片到document  
  12. + (BOOL)saveImage:(UIImage *)saveImage ImageName:(NSString *)imageName back:(void(^)(NSString *imagePath))back  
  13. {  
  14.     NSString *path = [SaveImage_Util getImageDocumentFolderPath];  
  15.     NSData *imageData = UIImagePNGRepresentation(saveImage);  
  16.     NSString *documentsDirectory = [NSString stringWithFormat:@"%@/", path];  
  17.     // Now we get the full path to the file  
  18.     NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:imageName];  
  19.     // and then we write it out  
  20.     NSFileManager *fileManager = [NSFileManager defaultManager];  
  21.     //如果文件路径存在的话  
  22.     BOOL bRet = [fileManager fileExistsAtPath:imageFile];  
  23.     if (bRet)  
  24.     {  
  25.         //        NSLog(@"文件已存在");  
  26.         if ([fileManager removeItemAtPath:imageFile error:nil])  
  27.         {  
  28.             //            NSLog(@"删除文件成功");  
  29.             if ([imageData writeToFile:imageFile atomically:YES])  
  30.             {  
  31.                 //                NSLog(@"保存文件成功");  
  32.                 back(imageFile);  
  33.             }  
  34.         }  
  35.         else  
  36.         {  
  37.               
  38.         }  
  39.           
  40.     }  
  41.     else  
  42.     {  
  43.         if (![imageData writeToFile:imageFile atomically:NO])  
  44.         {  
  45.             [fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];  
  46.             if ([imageData writeToFile:imageFile atomically:YES])  
  47.             {  
  48.                 back(imageFile);  
  49.             }  
  50.         }  
  51.         else  
  52.         {  
  53.             return YES;  
  54.         }  
  55.           
  56.     }  
  57.     return NO;  
  58. }  
  59. #pragma mark  从文档目录下获取Documents路径  
  60. + (NSString *)getImageDocumentFolderPath  
  61. {  
  62.     NSString *patchDocument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];  
  63.     return [NSString stringWithFormat:@"%@/Images", patchDocument];  
  64. }  
  65. @end  

以上内容仅供参考,部分内容来之网络,如有重复,请联系修改,谢谢!

欢迎各位同志的交流,如需demo可下载(免费)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值