ios 基本框架使用

1. sdwebImage使用:

1.1.基本使用

#import "ViewController2.h"
#import "UIImageView+WebCache.h"
#import "MJExtension.h"
#import "XmgVideo.h"
#import "GDataXMLNode.h"
#include "Main.h"
#import "AFNetworking.h"
#import "Person.h"
#import "Reachability.h"
#import "NSString+Hash.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 图片 下载 简单方法
    [self.myWebImage sd_setImageWithURL:[NSURL URLWithString:@"http://img5.mtime.cn/mg/2019/06/27/224744.68512147_120X90X4.jpg"]];
  
    // options 图片下载策略
    /*
     // 下载失败重新下载
        SDWebImageRetryFailed = 1 << 0,
       低优先级别,当uiscrollview 滚动的时候不下载
        SDWebImageLowPriority = 1 << 1,
        不做沙盒缓存
        SDWebImageCacheMemoryOnly = 1 << 2,
        图片下载一点,显示一点
        SDWebImageProgressiveDownload = 1 << 3,
        SDWebImageRefreshCached = 1 << 4,
        SDWebImageContinueInBackground = 1 << 5,
        SDWebImageHandleCookies = 1 << 6,
        SDWebImageAllowInvalidSSLCertificates = 1 << 7,
        SDWebImageHighPriority = 1 << 8,
        SDWebImageDelayPlaceholder = 1 << 9,
        SDWebImageTransformAnimatedImage = 1 << 10,
        SDWebImageAvoidAutoSetImage = 1 << 11,
        SDWebImageScaleDownLargeImages = 1 << 12
     */
    
    // 2. 图片下载 完整方法
//    [self.myWebImage sd_setImageWithURL:[NSURL URLWithString:@"http://img5.mtime.cn/mg/2019/06/27/224744.68512147_120X90X4.jpg"] placeholderImage:nil options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//        //receivedSize   已经下载大小
//        //expectedSize 总的大小
//    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//
//    }];
}

button设置图片  可以设置状态:UIControlStateNormal ,请求网络图片的时候

  // 通过  <UIButton+WebCache.h>
        [button sd_setImageWithURL:[NSURL URLWithString:square.icon] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"setup-head-default"]];
        // 通过<UIImageView +WebCache.h>
//        [button.imageView sd_setImageWithURL:[NSURL URLWithString:square.icon] placeholderImage:[UIImage imageNamed:@"setup-head-default"]];

2. 缓存清理 AppDelegate   内存告急回调

-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
    
    // 1.取消当前所有任务
    [[SDWebImageManager sharedManager] cancelAll];
    // 2. 清理缓存
    // 直接删除文件夹
    [[SDWebImageManager sharedManager].imageCache clearDiskOnCompletion:^{
        
    }];    
}

2.  ios Json解析方案:

苹果原生: NSJSONSerialization
 2.1. json 字符串 转 oc 对象
 2.2. oc 对象 转 jons字符串

-(void)touchesBegan1:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    NSString* test=@"{\"username\":\"xiaming\"}";
  //  NSString* test=@"[\"xiaonig\",\"xiaohei\"]";  // __NSSingleEntryDictionaryI
 //   NSString* test=@"\"error\"";  //   NSTaggedPointerString
  //    NSString* test=@"true";    // __NSCFBoolean
  //  NSString* test=@"null";    // NSNull

    // 把Json 转化为 OC 对象
    //   NSJSONReadingAllowFragments:  如果直接返回一个"error",不是标准json,一定要用这个,不用这个返回nil
    //kNilOptions  : 默认是这个,性能是最后的
    id obj = [NSJSONSerialization JSONObjectWithData:[test dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
    
    
    NSLog(@"%@",[obj class]);
    // OC 对象 转化 json 字符串
    NSDictionary* dict= @{
        @"username:":@"xiaming"
    };
    
    /* Returns YES if the given object can be converted to JSON data, NO otherwise. The object must have the following properties:
       - Top level object is an NSArray or NSDictionary
       - All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
       - All dictionary keys are NSStrings
       - NSNumbers are not NaN or infinity
    Other rules may apply. Calling this method or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
     oc - > json 条件
     1. 最外层是 字段或者 数组
     2.  元素必须是 NString NSNumber NSArray NSDictionary, or NSNull
     3.  所有的字典key 必须是 NString
     4.  NSNumbers 不能是null 或者 无穷大
    */

    
    BOOL isValid= [NSJSONSerialization isValidJSONObject:dict];
    NSLog(@"isValid=%d",isValid);
    NSData* data= [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    
}

  3.   ios xml 解析:

3.1.   XSXMLParser:  sax 方式解析
  // 1.创建 sax 解析器
   // 2. 设置代理
   3. 开始解析
   4. 代理中监听解析方法即可

person.xml 本地文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE students SYSTEM  "student.dtd">
 
<students>
   <student ID="1" movieName="xiaming" ></student>
   <student ID="2" movieName="xiaohei" ></student>
   <student ID="3" movieName="xiaoze" ></student>
 
</students>

XmgVideo:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface XmgVideo : NSObject

@property(nonatomic,assign) NSInteger ID;
@property(nonatomic,copy) NSString* movieName;

@end

NS_ASSUME_NONNULL_END

OC代码: 

 @interface ViewController2 ()<NSXMLParserDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *myWebImage;

@property(nonatomic,strong) NSMutableArray* videos;


@end

@implementation ViewController2


-(void)touchesBegan6:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    NSString* xmlPath = [[NSBundle mainBundle] pathForResource:@"person.xml" ofType:nil];
    
    NSString* str1 = [[NSString alloc] initWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil];
    
    NSData* data= [str1 dataUsingEncoding:NSUTF8StringEncoding];
    // 1.创建 sax 解析器
    NSXMLParser* parser= [[ NSXMLParser alloc] initWithData:data];
    // 2. 设置代理
    parser.delegate= self;
    // 3. 开始解析
    [parser parse];
    
  //  NSLog(@"%@",str1);
    
}
// 开始解析 xml 文档
-(void)parserDidStartDocument:(NSXMLParser *)parser{
    NSLog(@"start xml parse");
    
}
//  解析xml 每一个元素
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict{
// 每一个元素名字   每一个标签属性集合 attributeDict 
    NSLog(@"start--%@---%@",elementName,attributeDict);
  
    [self.videos addObject: [XmgVideo mj_objectWithKeyValues:attributeDict]];
    
}
// 解析xml 每一个元素的结束
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"end");
}
// 解析完成了
-(void)parserDidEndDocument:(NSXMLParser *)parser{
    
      NSLog(@"start xml end");
    
    NSLog(@"result==%@",self.videos);
}

@end

3.2.  第三方库:
   libxml2 :  存 c 的  , 支持dom/sax解析, 默认包含在ios  sdk中
   Gdataxml:  dom方式解析,google开发,基于 libxml2

1. 拖入 Gdataxml 库以后出现  问题

错误 提示:    提示: 
// libxml includes require that the target Header Search Paths contain
//
//   /usr/include/libxml2
//
// and Other Linker Flags contain  搜索  Other Linker Flags 添加   -lxml2
//
//   -lxml2

解决方式:

1. 添加  /usr/include/libxml2   配置 -lxml2  同理

 报错: Gdataxml  为MRC, 把MRC 不用管,直接ARC 编译

    错误: 

     解决: 

OC 代码: 

-(void)touchesBegan7:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    NSString* xmlPath = [[NSBundle mainBundle] pathForResource:@"person.xml" ofType:nil];
    NSString* str1 = [[NSString alloc] initWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil];
    NSData* data= [str1 dataUsingEncoding:NSUTF8StringEncoding];
    
    GDataXMLDocument* doc= [[GDataXMLDocument alloc] initWithData:data options:kNilOptions error:nil];
    
   NSArray* eles=  [doc.rootElement elementsForName:@"student"];
    
    for (GDataXMLElement* ele in eles) {
        NSLog(@"%@", ele);
        XmgVideo* video= [XmgVideo new];
        video.movieName= [ele attributeForName:@"movieName"].stringValue;
        video.ID =  [ele attributeForName:@"ID"].stringValue.integerValue  ;
        [self.videos addObject:video];
    }
    NSLog(@"结果:%@",self.videos);
}

  4.   文件压缩:  第三方压缩框架 ZipArchive 

如果报错,添加第三方库: 

OC代码实现 :

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self zip];
}

-(void)unZip
{
    /*
     第一个参数:要解压的文件在哪里
     第二个参数:文件要放到什么地方
     */
    [Main unzipFileAtPath:@"/Users/xiaomage/Desktop/vvv.zip" toDestination:@"/Users/xiaomage/Desktop/yy"];
}
-(void)zip
{
    NSArray *arrayM =@[
                       @"/Users/denganzhi/Desktop/from/1.png",
                       @"/Users/denganzhi/Desktop/from/2.png",
                       @"/Users/denganzhi/Desktop/from/3.png"
                       ];
    /*
     第一个参数:创建的zip放在哪里
     第二个参数:要压缩哪些文件
     */
    [Main createZipFileAtPath:@"/Users/denganzhi/Desktop/demo.zip" withFilesAtPaths:arrayM];
}

-(void)zip2
{
    /*
     第一个参数:创建的zip放在哪里
     第二个参数:要压缩的文件路径
     */
    
    [Main createZipFileAtPath:@"/Users/denganzhi/Desktop/vvv.zip" withContentsOfDirectory:@"/Users/denganzhi/Desktop/from"];
}

  5.    NSURLSessionTask 和 mj 字典转模型使用


//  NSURLSessionTask 和 mj 字典转模型使用
-(void)touchesBegan9:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"%@",@"发送网络请求");
    
    // MJEXtensio 别名配置,字典中名字 和模型中  对应不上
    [XmgVideo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
            @"ID":@"id"
        };
    }];
    
    //1. 创建 NSURLSession
    NSURLSession * session= [NSURLSession sharedSession];
    // 2.  根据请求对象 创建 task
    NSURLRequest* request= [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.m.mtime.cn/PageSubArea/TrailerList.api"]];
    
   NSURLSessionTask* dataTask=  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       // 解析数据
      // NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
       
     
       NSDictionary* dictM =  [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
       
       // 字典转模型  MJExension
          NSArray *arrayM = dictM[@"trailers"];
               //字典转模型,   通过类工厂方法 或者
               // kvc
//        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:arrayM.count];
//        for (NSDictionary *dict in arrayM) {
//            [arr addObject:[XMGVideo videoWithDict:dict]];
//        }
              
       // mj NSarray 字典 转 模型
       self.videos = [XmgVideo mj_objectArrayWithKeyValuesArray:arrayM];
       NSLog(@"%@",self.videos);
    }];
    
    // 启动任务
    [dataTask resume];
}

 6 AFN 使用

 6.1. AFN 发送 GET 请求 | AFN 下载文件

-(void)touchesBegan10:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSDictionary *paramDict = @{
                                 @"username":@"Cehae",
                                 @"password":@"Cehae"
                                 };    //2.发送GET请求/*

    AFHTTPSessionManager* manager= [AFHTTPSessionManager manager];
    // 1. AFN 发送 GET 请求
    [manager GET:@"http://192.168.1.162:8080/JsonServlet/GsonServlet" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //AFN 返回字典,直接字典转模型即可
        Person* person=[Person mj_objectWithKeyValues:responseObject];
        NSLog(@"person=%@",person);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    //2. AFN 下载文件
 NSURL *url = [NSURL URLWithString:@"http://img5.mtime.cn/mg/2019/06/27/104649.48931556_120X90X4.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //监听下载进度
        /*
         downloadProgress.completedUnitCount      已经下载的数据大小
         downloadProgress.totalUnitCount);       文件数据的总大小
         */
        
//        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
        
        // kvo 监听属性变化
        [downloadProgress addObserver:self forKeyPath:@"completedUnitCount" options:kNilOptions context:nil];
        
       } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
           NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
           //targetPath 临时文件路径
           NSLog(@"targetPath:%@",targetPath);        NSLog(@"fullPath:%@",fullPath);
           // 真实文件路径,返回真实文件路径即可,会自动拷贝到真实文件路径中
           return [NSURL fileURLWithPath:fullPath];
       } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {        NSLog(@"%@",filePath);
       }];    //3.执行Task
       [download resume];
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(NSProgress*)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    NSLog(@"kvo--%f", object.completedUnitCount*1.0/object.totalUnitCount);
    
}

6.2.  AFN 上传文件 POST 使用

-(void)touchesBegan11:(NSSet<UITouch *> *)touches11 withEvent:(UIEvent *)event{
     AFHTTPSessionManager* manager= [AFHTTPSessionManager manager];
    NSString* url=@"http://192.168.2.236:8080/JsonServlet/FileUploadServlet";
  
    /**
     <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
         用户名 <input type="text" name="name" /> <br /> <br />
         照片 <input type="file" name="photo1" /> <br /> <br />
     </form>
     */
    // 这里相当于用户名
    NSDictionary* dict= @{
        @"name":@"yyy"
    };
 
    //1. OC 封装上传文件方法
//    [manager uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromData:<#(nullable NSData *)#> progress:<#^(NSProgress * _Nonnull uploadProgress)uploadProgressBlock#> completionHandler:<#^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error)completionHandler#>]
    
     // 2.  OC 模拟表单方式上传文件
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    

    
   [manager POST:url parameters:dict
constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
       UIImage* image= [UIImage imageNamed:@"setting_about_pic"];
       NSData* imageData= UIImagePNGRepresentation(image);
    // 这里 设置 type
       [formData appendPartWithFileData:imageData name:@"file" fileName:@"setting_about_pic.png" mimeType:@"image/png"];
     
       
       // 上传本地文件,单做  application/octet-stream 流处理即可,不用管图片类型
      NSURL* url=[NSURL fileURLWithPath:@"/Users/denganzhi/Desktop/ios开发.txt"];
//       [formData appendPartWithFileURL:url name:@"file" fileName:@"wwww" mimeType:@"application/octet-stream" error:nil];
       
       
     [formData appendPartWithFileURL:url name:@"file" error:nil];
       
       
   } progress:^(NSProgress * _Nonnull uploadProgress) {
       
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       NSLog(@"suc");
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       NSLog(@"%@",error);
   }];
    
    
  
}

 6.3. AFN序列化:

   AFN自动把json 转化为oc 对象默认
如果是xml:    manager.requestSerializer= [AFXMLParserResponseSerializer serializer];

如果不是xml、json : 
  manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  // 自己添加 执行类型 
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
      

6.4.  网络监测: 可以用苹果提供demo ,也可以用AFN

-(void)afn
{
    
    //1.创建网络监听管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*
     AFNetworkReachabilityStatusUnknown          = 未知
     AFNetworkReachabilityStatusNotReachable     = 没有联网
     AFNetworkReachabilityStatusReachableViaWWAN = 3G
     AFNetworkReachabilityStatusReachableViaWiFi = wifi
     */
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@" 没有联网");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"wifi");
                break;
            default:
                break;
        }
        
    }];
    
    [manager startMonitoring];
}

7.  UIWevView 使用

 1.UIWebView 使用:  案例,前进、后退功能

#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *myWebView;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *goBackBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *foWard;

@end



@implementation ViewController

- (IBAction)goBack:(id)sender {
    [self.myWebView goBack];
}
- (IBAction)forWard:(id)sender {
    [self.myWebView goForward];
}
- (IBAction)reload:(id)sender {
    [self.myWebView reload];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    NSURLRequest* rq= [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    
  //      NSURL *url = [[NSBundle mainBundle]URLForResource:@"text.html" withExtension:nil];
 //   [self.myWebView loadRequest:[NSURLRequest requestWithURL:url]];


// https://www.jianshu.com/p/f328f4ae397f
//添加 网页  UIDataDetectorTypeAll检测电话、网址和邮箱
   self.webView.dataDetectorTypes = UIDataDetectorTypeAll;
    
    [self.myWebView loadRequest:rq];
    self.myWebView.delegate= self;
    // 网页自动适应webview
    self.myWebView.scalesPageToFit = YES;
}

//1.开始加载的时候调用
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
}
//加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
     NSLog(@"webViewDidFinishLoad");
    // 设置是否可以前进、后退按钮
    self.goBackBtn.enabled = self.myWebView.canGoBack;
    self.foWard.enabled = self.myWebView.canGoForward;
    
    NSString* str= [self.myWebView stringByEvaluatingJavaScriptFromString:@"sum();"];
    
    NSLog(@"sum=%@",str);
    
    
}
//加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
     NSLog(@"didFailLoadWithError");
}

//
//每次加载请求的时候会先带哟, 请求拦截
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"=-----%@",request.URL.absoluteString);
   if ([request.URL.absoluteString containsString:@"life"]) {
        return NO;
    }
   return YES;
}



@end

效果图:

 7.2.  oc 与js 的互相调用: 

   7.2.1   oc 对js 调用: 
      //加载完成 , 直接 调用js 中方法即可
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
   NSString* str= [self.myWebView stringByEvaluatingJavaScriptFromString:@"sum();"];

   js 对oc 调用:
//js 每次加载请求的时候  该代理 方法会回调, 请求拦截,获取拦截js 中协议 ,解析,调用oc 即可
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{}
 

text.html: 

<html>
    <!-- 网页的描述信息 -->
    <head>
        <meta charset="UTF8">
        <title>123</title>

        <script>
            function show()
            {
                alert(document.title);
            }
        
        // 这里是 js 调用 oc
           function repost()
            {
                // 这里不能用 xmg://callWithNumber:andContent:?10086&1122333
                //  这里不能用: 会报错
                location.href = "xmg://callWithNumber_andContent_?10086&1122333";
            }
        // 案例 , oc 调用 js
            function sum()
            {
                return 1 + 1;
            }
        </script>
    </head>
    
    <!-- 网页的具体内容-->
    <body>
        <button style="background: green; height:50px; width:200px;" onclick="repost();">点击我</button>
    </body>
</html>

oc 代码实现: 



#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *myWebView;


@end



@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
   
  // NSURLRequest* rq= [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    
        NSURL *url = [[NSBundle mainBundle]URLForResource:@"text.html" withExtension:nil];
    [self.myWebView loadRequest:[NSURLRequest requestWithURL:url]];
    
    [self.myWebView loadRequest:rq];
    self.myWebView.delegate= self;
    // 网页自动适应webview
    self.myWebView.scalesPageToFit = YES;
}

//1.开始加载的时候调用
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
}
//加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
     NSLog(@"webViewDidFinishLoad");
  
  
    NSString* str= [self.myWebView stringByEvaluatingJavaScriptFromString:@"sum();"];
    
    NSLog(@"sum=%@",str);
    
    
}
//加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
     NSLog(@"didFailLoadWithError");
}

//
//每次加载请求的时候会先带哟, 请求拦截
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//    NSLog(@"=-----%@",request.URL.absoluteString);
//    if ([request.URL.absoluteString containsString:@"life"]) {
//        return NO;
//    }
//    return YES;
    
    // 只有一个参数
     NSLog(@"###%@",request.URL.absoluteString);
        
        NSString *requestUrl =request.URL.absoluteString;
        NSString *xmgStr =@"xmg://";
        
        
        if ([requestUrl hasPrefix:xmgStr]) {
            NSLog(@"JS调用OC方法");
            
            //1.把方法名称拿出来
            NSString *mtr = [requestUrl substringFromIndex:xmgStr.length];
    //        xmg://callWithNumber_?10086
            NSLog(@"把方法名称拿出来:%@",mtr);
            
                NSArray *array =[mtr componentsSeparatedByString:@"?"];
            NSLog(@"%@",array);
            
            //用第二个参数替换第一个参数
            mtr = [[array firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            NSLog(@"%@---",mtr);
            
            
            SEL methedSEL = NSSelectorFromString(mtr);
            
            //处理参数
            NSString *param = [array lastObject];
            //2.调用方法
            [self performSelector:methedSEL withObject:param];
            return NO;
        }
         
        
// 有2个参数
//        if ([requestUrl hasPrefix:xmgStr]) {
//            NSLog(@"JS调用OC方法");
//
//            //1.把方法名称拿出来
//            NSString *mtr = [requestUrl substringFromIndex:xmgStr.length];
//            //        xmg://callWithNumber_?10086
//            NSLog(@"把方法名称拿出来:%@",mtr);
//
//            NSArray *array =[mtr componentsSeparatedByString:@"?"];
//            NSLog(@"%@",array);
//
//            //用第二个参数替换第一个参数
//            mtr = [[array firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
//            // callWithNumber:andContent:
//            NSLog(@"%@---",mtr);
//
//
//            SEL methedSEL = NSSelectorFromString(mtr);
//
//            //处理参数
//            NSString *param = [array lastObject];
//            NSArray *paramArray =[param componentsSeparatedByString:@"&"];
//
//            NSString *param1 = [paramArray firstObject];
//             NSString *param2 = [paramArray lastObject];
//            //2.调用方法
//            [self performSelector:methedSEL withObject:param1 withObject:param2];
//            return NO;
//        }
        
        return YES;
    
    
}

-(void)call
{
    NSLog(@"打电话");
}

-(void)callWithNumber:(NSString *)number
{
    NSLog(@"电话给%@",number);
}

-(void)callWithNumber:(NSString *)number andContent:(NSString *)Content
{
    NSLog(@"电话给%@,告诉他%@",number,Content);
}


@end

============================================================

源码大纲内容: 

ViewController2:
sdwebimage、
json->oc  和 oc->json 转化
xml 解析
ZipArhiver 文件压缩、解压
NSURLSessionTask
AFHTTPSessionManager: GET|download|post 上传文件
afn: 网络监测
md5使用

ViewController: 
uiwebview 使用案例,前进、后退
oc 和 js 互调

源码地址:https://download.csdn.net/download/dreams_deng/12505751

============================================================

猜你喜欢

转载自blog.csdn.net/dreams_deng/article/details/106575762