Apptimize\Optimizely如何在iOS上运行?

Ode*_*gev 15 cocoa-touch objective-c ab-testing ios apptimize

我试图找出一些关于"幕后"实现的一些事情,即直接从Apptimize或Optimizely上的Web控制台动态操作UI元素.

更具体地说,我想了解以下内容:

1)客户端代码(iOS)如何将视图层次结构发送到Web服务器,以便当您在Web仪表板上选择任何UI元素时,它立即显示在iOS客户端上?

我看到了FLEX,以及它如何设法获取视图层次结构,但我不明白iphone客户端如何"知道"在Web仪表板中选择哪个视图.

2)此外,在Apptimize中,我可以从Web仪表板中选择任何UI元素,更改其文本或颜色,它将立即在应用程序中更改.不仅如此,只需拥有SDK即可添加任何代码.

我所做的更改(文本,背景颜色等)将保留在应用程序的所有未来会话中.如何实施?

我猜他们正在使用某种反思,但他们怎样才能让它适用于所有用户以及所有未来的会话?客户端代码如何找到正确的UI元素?以及它如何在UITableViewCell上运行?

3)每次加载UIViewController都可以检测到吗?即在每个viewDidLoad上获得回调?如果是这样,怎么样?

看下面的一些截图:

在此输入图像描述

在此输入图像描述

Bar*_*raa 12

我的名字是Baraa,我是Optimizely移动团队的软件工程实习生,所以我可以分享一些关于Optimizely SDK如何在Android和iOS上运行的高级见解.

在iOS上,Optimizely SDK使用称为swizzling的技术.这允许我们根据数据文件中当前活动的任何实验将可视更改应用于应用程序.

在Android上,Optimizely使用反射将SDK附加为交互和生命周期事件的侦听器,以根据数据文件中活动的任何实验将可视更改应用于应用程序.

有关我们在iOS上调查的方法的完整列表以及我们在Android上拦截的侦听器,请查看此帮助文章:https://help.optimizely.com/hc/en-us/articles/205014107-How-Optimizely- S-的SDK-工作-SDK-订单的执行中,实验-激活和目标执行#

  • 这非常有用,谢谢@Baraa (3认同)
  • 视图通过它们在视图层次结构中的位置来标识,类似于CSS选择器在Web上的工作方式. (3认同)

Vik*_*ica 5

我想知道同样的,并且找不到明确的答案,所以这是我(希望)受过教育的猜测:

由于运行时环境,在Cocoa(-Touch)中使用面向方面编程(AOP)实际上并不困难,其中编写规则以在其他类方法调用中挂钩.

如果你google for AOPObjective-C,会弹出几个很好地包装运行时代码的库.

例如steinpete的Aspect库:

[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
    NSLog(@"View Controller %@ will appear animated: %tu", aspectInfo.instance, animated);
} error:NULL];
Run Code Online (Sandbox Code Playgroud)

这个方法调用

+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
                      withOptions:(AspectOptions)options
                       usingBlock:(id)block
                            error:(NSError **)error {
    return aspect_add((id)self, selector, options, block, error);
}
Run Code Online (Sandbox Code Playgroud)

电话 aspect_add()

static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) {
    NSCParameterAssert(self);
    NSCParameterAssert(selector);
    NSCParameterAssert(block);

    __block AspectIdentifier *identifier = nil;
    aspect_performLocked(^{
        if (aspect_isSelectorAllowedAndTrack(self, selector, options, error)) {
            AspectsContainer *aspectContainer = aspect_getContainerForObject(self, selector);
            identifier = [AspectIdentifier identifierWithSelector:selector object:self options:options block:block error:error];
            if (identifier) {
                [aspectContainer addAspect:identifier withOptions:options];

                // Modify the class to allow message interception.
                aspect_prepareClassAndHookSelector(self, selector, error);
            }
        }
    });
    return identifier;
}
Run Code Online (Sandbox Code Playgroud)

它再次调用其他几个非常可怕的函数来完成运行时繁重的工作

static void aspect_prepareClassAndHookSelector(NSObject *self, SEL selector, NSError **error) {
    NSCParameterAssert(selector);
    Class klass = aspect_hookClass(self, error);
    Method targetMethod = class_getInstanceMethod(klass, selector);
    IMP targetMethodIMP = method_getImplementation(targetMethod);
    if (!aspect_isMsgForwardIMP(targetMethodIMP)) {
        // Make a method alias for the existing method implementation, it not already copied.
        const char *typeEncoding = method_getTypeEncoding(targetMethod);
        SEL aliasSelector = aspect_aliasForSelector(selector);
        if (![klass instancesRespondToSelector:aliasSelector]) {
            __unused BOOL addedAlias = class_addMethod(klass, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
            NSCAssert(addedAlias, @"Original implementation for %@ is already copied to %@ on %@", NSStringFromSelector(selector), NSStringFromSelector(aliasSelector), klass);
        }

        // We use forwardInvocation to hook in.
        class_replaceMethod(klass, selector, aspect_getMsgForwardIMP(self, selector), typeEncoding);
        AspectLog(@"Aspects: Installed hook for -[%@ %@].", klass, NSStringFromSelector(selector));
    }
}
Run Code Online (Sandbox Code Playgroud)

包括方法调配.


很容易看出,我们这里有一个工具,可以让我们发送应用程序的当前状态,在网页中重新构建它,同时也可以操作现有代码中的对象.
当然这只是一个起点.您将需要一个Web应用程序来组装应用程序并将其发送给用户.


就个人而言,我从未使用AOP执行这么复杂的任务,但我用它来教授所有视图控制器跟踪功能

- (void)setupViewControllerTracking
{
    NSError *error;
    @weakify(self);
    [UIViewController aspect_hookSelector:@selector(viewDidAppear:)
                              withOptions:AspectPositionAfter
                               usingBlock:^(id < AspectInfo > aspectInfo) {
                                   @strongify(self);
                                   UIViewController *viewController = [aspectInfo instance];
                                   NSArray *breadCrumbs = [self breadCrumbsForViewController:viewController];

                                   if (breadCrumbs.count) {
                                       NSString *pageName = [NSString stringWithFormat:@"/%@", [breadCrumbs componentsJoinedByString:@"/"]];
                                       [ARAnalytics pageView:pageName];
                                   }
                               } error:&error];
}
Run Code Online (Sandbox Code Playgroud)

更新

我玩了一下,并能够创建一个原型.如果添加到项目中,它会将所有视图控制器背景颜色更改为蓝色,并在5秒后将所有生命视图控制器背景更改为橙色,方法是使用AOP和动态方法添加.

源代码:https://gist.github.com/vikingosegundo/0e4b30901b9498ae4b7b

5秒由通知触发,但显然这可能是网络事件.


更新2

我教我的原型打开网络接口并接受背景的rgb值.
这将是在模拟器中运行

http://127.0.0.1:8080/color/<r>/<g>/<b>/
http://127.0.0.1:8080/color/50/120/220/
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我用OCFWebServer

//
//  ABController.m
//  ABTestPrototype
//
//  Created by Manuel Meyer on 12.05.15.
//  Copyright (c) 2015 Manuel Meyer. All rights reserved.
//

#import "ABController.h"

#import <Aspects/Aspects.h>
#import <OCFWebServer/OCFWebServer.h>
#import <OCFWebServer/OCFWebServerRequest.h>
#import <OCFWebServer/OCFWebServerResponse.h>


#import <objc/runtime.h>
#import "UIViewController+Updating.h"
#import "UIView+ABTesting.h"


@import UIKit;

@interface ABController ()
@property (nonatomic, strong) OCFWebServer *webserver;
@end
@implementation ABController


void _ab_register_ab_notificaction(id self, SEL _cmd)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:NSSelectorFromString(@"ab_notifaction:") name:@"ABTestUpdate" object:nil];
}


void _ab_notificaction(id self, SEL _cmd, id userObj)
{
    NSLog(@"UPDATE %@", self);
}


+(instancetype)sharedABController{
    static dispatch_once_t onceToken;
    static ABController *abController;
    dispatch_once(&onceToken, ^{

        OCFWebServer *server = [OCFWebServer new];

        [server addDefaultHandlerForMethod:@"GET"
                              requestClass:[OCFWebServerRequest class]
                              processBlock:^void(OCFWebServerRequest *request) {
                                  OCFWebServerResponse *response = [OCFWebServerDataResponse responseWithText:[[[UIApplication sharedApplication] keyWindow] listOfSubviews]];
                                  [request respondWith:response];
                              }];

        [server addHandlerForMethod:@"GET"
                          pathRegex:@"/color/[0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3}/"
                       requestClass:[OCFWebServerRequest class]
                       processBlock:^(OCFWebServerRequest *request) {
                           NSArray *comps = request.URL.pathComponents;
                           UIColor *c = [UIColor colorWithRed:^{ NSString *r = comps[2]; return [r integerValue] / 255.0;}()
                                                        green:^{ NSString *g = comps[3]; return [g integerValue] / 255.0;}()
                                                         blue:^{ NSString *b = comps[4]; return [b integerValue] / 255.0;}()
                                                        alpha:1.0];

                           [[NSNotificationCenter defaultCenter] postNotificationName:@"ABTestUpdate" object:c];
                           OCFWebServerResponse *response = [OCFWebServerDataResponse responseWithText:[[[UIApplication sharedApplication] keyWindow] listOfSubviews]];
                           [request respondWith:response];
                       }];

        dispatch_async(dispatch_queue_create(".", 0), ^{
            [server runWithPort:8080];
        });

        abController = [[ABController alloc] initWithWebServer:server];
    });
    return abController;
}

-(instancetype)initWithWebServer:(OCFWebServer *)webserver
{
    self = [super init];
    if (self) {
        self.webserver = webserver;
    }
    return self;
}


+(void)load
{
    class_addMethod([UIViewController class], NSSelectorFromString(@"ab_notifaction:"), (IMP)_ab_notificaction, "v@:@");
    class_addMethod([UIViewController class], NSSelectorFromString(@"ab_register_ab_notificaction"), (IMP)_ab_register_ab_notificaction, "v@:");

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.00001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self sharedABController];
    });
    [UIViewController aspect_hookSelector:@selector(viewDidLoad)
                              withOptions:AspectPositionAfter
                               usingBlock:^(id<AspectInfo> aspectInfo) {

                                   dispatch_async(dispatch_get_main_queue(),
                                                  ^{
                                                      UIViewController *vc = aspectInfo.instance;
                                                      SEL selector = NSSelectorFromString(@"ab_register_ab_notificaction");
                                                      IMP imp = [vc methodForSelector:selector];
                                                      void (*func)(id, SEL) = (void *)imp;func(vc, selector);
                                                });
                               } error:NULL];

    [UIViewController aspect_hookSelector:NSSelectorFromString(@"ab_notifaction:")
                              withOptions:AspectPositionAfter
                               usingBlock:^(id<AspectInfo> aspectInfo, NSNotification *noti) {

                                   dispatch_async(dispatch_get_main_queue(),
                                                  ^{
                                                      UIViewController *vc = aspectInfo.instance;
                                                      [vc updateViewWithAttributes:@{@"backgroundColor": noti.object}];
                                                  });
                               } error:NULL];
}
@end
Run Code Online (Sandbox Code Playgroud)
//
//  UIViewController+Updating.m
//  ABTestPrototype
//
//  Created by Manuel Meyer on 12.05.15.
//  Copyright (c) 2015 Manuel Meyer. All rights reserved.
//

#import "UIViewController+Updating.h"

@implementation UIViewController (Updating)
-(void)updateViewWithAttributes:(NSDictionary *)attributes
{
    [[attributes allKeys] enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {

        if ([obj isEqualToString:@"backgroundColor"]) {

                [self.view setBackgroundColor:attributes[obj]];
        }
    }];
}
@end
Run Code Online (Sandbox Code Playgroud)

完整代码:https://github.com/vikingosegundo/ABTestPrototype