终端接入指引-iOS版本

1. 引入头文件,声明协议

(1.1)编译对应平台所需的Sonic.framework ,在Build目录找到.framework文件

(1.2)将Sonic.framework引入主工程

AppDelegate中注册SonicURLProtocol

  1. [NSURLProtocol registerClass:[SonicURLProtocol class]];

(1.3)引入 @import Sonic;

  1. @interface SonicWebViewController : UIViewController<SonicSessionDelegate,UIWebViewDelegate>

2. 实现SonicSessionDelegate

  1. #pragma mark - Sonic Session Delegate
  2.  
  3. /*
  4. * sonic请求发起前回调
  5. */
  6. - (void)sessionWillRequest:(SonicSession *)session
  7. {
  8. //可以在请求发起前同步Cookie等信息
  9. }
  10.  
  11. /*
  12. * sonic要求webView重新load指定request
  13. */
  14. - (void)session:(SonicSession *)session requireWebViewReload:(NSURLRequest *)request
  15. {
  16. [self.webView loadRequest:request];
  17. }

3. 在WebView的ViewController中接入Sonic使用 (Sample:SonicWebViewController)

  1. /*
  2. * 在初始化ViewController的时候发起sonic的请求
  3. */
  4. - (instancetype)initWithUrl:(NSString *)aUrl
  5. {
  6. if (self = [super init]) {
  7.  
  8. self.url = aUrl;
  9.  
  10. self.clickTime = (long long)[[NSDate date]timeIntervalSince1970]*1000;
  11.  
  12. //使用sonic链接创建一个会话
  13. [[SonicClient sharedClient] createSessionWithUrl:self.url withWebDelegate:self];
  14. }
  15. return self;
  16. }
  17.  
  18. /*
  19. * 在初始化WebView之后立即发起带有sonic信息的请求
  20. */
  21. - (void)loadView
  22. {
  23. [super loadView];
  24.  
  25. self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
  26. self.webView.delegate = self;
  27. self.view = self.webView;
  28.  
  29. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
  30.  
  31. /*
  32. * 查询当前ViewController是否成功创建sonic会话,如果已经创建,那么包装request成sonic请求,以便在NSURLProtocol层拦截
  33. * 否则走正常模式加载请求,不会在NSURLProtocol层拦截
  34. */
  35. if ([[SonicClient sharedClient] sessionWithWebDelegate:self]) {
  36. [self.webView loadRequest:sonicWebRequest(request)];
  37. }else{
  38. [self.webView loadRequest:request];
  39. }
  40. }

4. 调用获取差异的接口,传递sonic会话的结果信息

  1. /*
  2. * 此接口由页面驱动,由前端sonic组件向终端发起请求获取会话结果
  3. */
  4. - (void)getDiffData:(NSDictionary *)option withCallBack:(JSValue *)jscallback
  5. {
  6. /*
  7. * 根据发起sonic会话的ViewController来查询需要的结果
  8. */
  9. [[SonicClient sharedClient] sonicUpdateDiffDataByWebDelegate:self.owner completion:^(NSDictionary *result) {
  10.  
  11. /*
  12. * 这里将result传递回页面即可
  13. */
  14. NSData *json = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
  15. NSString *jsonStr = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
  16.  
  17. JSValue *callback = self.owner.jscontext.globalObject;
  18. [callback invokeMethod:@"getDiffDataCallback" withArguments:@[jsonStr]];
  19.  
  20. }];
  21. }

5. 在WebDelegate销毁的时候移除WebDelegate对应的Session

  1. - (void)dealloc
  2. {
  3. [[SonicClient sharedClient] removeSessionWithWebDelegate:self];
  4. }