美文网首页iOS iOS Developer
从零开始设计搭建ios App框架(十四)

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

作者: 潇水渔翁 | 来源:发表于2016-10-08 18:25 被阅读121次

H5交互


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

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

#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>

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

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

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

#pragma mark-
@interface PGJSObject : NSObject<PGJSObjectProtocol>
@property(nonatomic, weak)id<PGJSObjectDelegate> 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<PGJSObjectDelegate>
@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脚本

<script>

    //业务场景
    if(typeof ServiceType == "undefined"){
        var ServiceType = {
            ServiceType_Type1: 1,
            ServiceType_Type2: 2,
            ServiceType_Type3: 3,
            ServiceType_Type4: 4,
            ServiceType_Type5: 5,
            ServiceType_Type6: 6
        }
    }

    //JS --> Native
    //param 为json字符串
    function wakeUpNative(type, param) {
        var str = "{\"type\":"+type+",\"param\":\""+param+"\"}";
        window.UCJSObject.wakeUpNativeObject(str)
    }

    //Native --> JS
    function wakeUpJS(type, param) {

        switch (type) {
            case ServiceType.ServiceType_Type1: {
                alert("apptojs");
                break;
            }
            case ServiceType.ServiceType_Type2: {
                alert(param);
                break;
            }
        }
    }

</script>

调用示例:

        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框架(十四)

    本文链接:https://www.haomeiwen.com/subject/tqwtyttx.html