从零开始设计搭建ios App框架(十四)

H5交互


OC与JS的交互实现方式有很多,之前用的比较多的是WebViewJavaScriptBridge,但在IOS7之后,苹果将JavaScriptCore框架开放。因此,这篇文章不讲理论(其实我也讲不清楚,怕误导,莫怪莫怪),主要讲的是JavaScriptCore的实际使用。

JS交互无非就是js与oc之间的数据传递,我们可以根据业务逻辑定义一些业务编号,如js调用oc原生的登录界面,下单界面,也可以是相机拍照等业务。注意这个编号的值js与oc要一至。

#import 
#import 

typedef NS_ENUM(NSInteger, UCJSType) {
    EPGJSType_Login = 1,//登录
    EPGJSType_Order,//下单
    EPGJSType_OpenPage_Coupon,//打开优惠券
    
    EPGJSType_Error,//出错时用
};

#pragma mark -
@protocol PGJSObjectDelegate 
@optional
- (void)jsReponse:(UCJSType)type params:(NSObject *)params;
- (void)jsErrorMessage:(NSString *)message;
@end

#pragma mark-
@protocol PGJSObjectProtocol 
//JS调用此方法并传递参数
- (void)wakeUpNativeObject:(NSString *)message;
@end

#pragma mark-
@interface PGJSObject : NSObject
@property(nonatomic, weak)id jsDelegate;

//生成调用JS方法的字符串
- (NSString *)wakeUpNativeJSType:(NSInteger)type param:(NSString *)params;

@end

@implementation PGJSObject

//生成调用JS方法的字符串
- (NSString *)wakeUpNativeJSType:(NSInteger)type param:(NSString *)params
{
    NSString *szParams = [NSString stringWithFormat:@"wakeUpJS(%ld,'%@')",(long)type, params];
    
    return szParams;
}

#pragma mark -
//JS调用此方法并传递参数
- (void)wakeUpNativeObject:(NSString *)message
{
    if(message == nil || [message isKindOfClass:[NSNull class]])
    {
        if(self.jsDelegate && [self.jsDelegate respondsToSelector:@selector(jsErrorMessage:)])
        {
            [self.jsDelegate jsErrorMessage:@"参数为空"];
        }
        return;
    }
    
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:[message dataUsingEncoding:NSUTF8StringEncoding]
                                                            options:kNilOptions
                                                              error:nil];
    
    UCJSType type = [[dicInfo objectForKey:@"type" type:EDictionTypeInteger] integerValue];
    NSObject *obj = [dicInfo objectForKey:@"param"];
    
    if(self.jsDelegate && [self.jsDelegate respondsToSelector:@selector(jsReponse:params:)])
    {
        [self.jsDelegate jsReponse:type params:obj];
    }
}

@end

PGWebBaseController.h

#import "PGWebBaseController.h"
#import "PGJSObject.h"

@interface PGJSBaseController : PGWebBaseController
@property(nonatomic, strong)PGJSObject *jsObj;
@end

PGWebBaseController.m

@interface PGJSBaseController ()
@property(nonatomic, strong)JSContext *jsContext;
@end

@implementation PGJSBaseController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.jsObj = [[PGJSObject alloc] init];
    self.jsObj.jsDelegate = self;
}

- (void)createInitData
{
    [super createInitData];
    
    WEAKSELF
    self.webViewDidFinishLoadBlock = ^(UIWebView *webView) {
        weakSelf.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        weakSelf.jsContext[@"UCJSObject"] = weakSelf.jsObj;
    };
}

#pragma mark -
- (void)jsReponse:(UCJSType)type params:(NSObject *)params
{
    NSString *str = [NSString stringWithFormat:@"type: %@, param: %@", @(type).stringValue, params];
    NSLog(@"====> %@",str);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showMsg:str];
    });
}

- (void)jsErrorMessage:(NSString *)message
{
}

@end

web页面中的js脚本


调用示例:

        PGH5JsController *controller = [[PGH5JsController alloc] initWithTitle:@"H5交互实例"];
        [self pushNewViewController:controller];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"nativeInteraction" ofType:@"html"];
        NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        [controller loadWebRequestWithHtmlString:htmlString];

哈哈,完了,不好意思全是代码!!

你可能感兴趣的:(从零开始设计搭建ios App框架(十四))