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) {
//
//    }];
}

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;" οnclick="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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章