iOS使用
构建声波框架 将Sonic.framework添加到主项目中框架里面,sdk。
进行下面的代码进行初始化.
[NSURLProtocol registerClass:[SonicURLProtocol class]];
@interface SonicWebViewController : UIViewController
SonicSessionDelegate代理
#pragma mark - Sonic Session Delegate
* 调用回来时发送请求。
- (void)sessionWillRequest:(SonicSession *)session;
*当Sonic要求WebView重新加载时回调,例如模板更改或发生错误。
- (void)session:(SonicSession *)session requireWebViewReload:(NSURLRequest *)request
{
[self.webView loadRequest:request];
}
步骤3:在WebView ViewController中使用Sonic
- (instancetype)initWithUrl:(NSString *)aUrl
{
if (self = [super init]) {
self.url = aUrl;
[[SonicClient sharedClient] createSessionWithUrl:self.url withWebDelegate:self];
}
return self;
}
* 在WebView初始化后立即发送Sonic属性的请求。
- (void)loadView
{
[super loadView];
self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
self.webView.delegate = self;
self.view = self.webView;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
* SonicSession不为空.
if ([[SonicClient sharedClient] sessionWithWebDelegate:self]) {
[self.webView loadRequest:sonicWebRequest(request)];
}else{
[self.webView loadRequest:request];
}
}
通过JavaScript回调与网站交互。
- (void)getDiffData:(NSDictionary *)option withCallBack:(JSValue *)jscallback
{
* ViewController发送Sonic请求并通过回调返回结果。
[[SonicClient sharedClient] sonicUpdateDiffDataByWebDelegate:self.owner completion:^(NSDictionary *result) {
* 返回结果。
NSData *json = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
JSValue *callback = self.owner.jscontext.globalObject;
[callback invokeMethod:@"getDiffDataCallback" withArguments:@[jsonStr]];
}];
}
- (void)dealloc
{
[[SonicClient sharedClient ] removeSessionWithWebDelegate:self ];
}
下载最新的Demo ---- https://github.com/Tencent/VasSonic 里面包含了安卓,iOS....
网友评论