Skip to content

Commit 583c538

Browse files
committed
cleanup DemoSwiftApp
1 parent 2f01f3c commit 583c538

File tree

6 files changed

+50
-41
lines changed

6 files changed

+50
-41
lines changed

DemoSwiftApp/AppDelegate.swift

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -47,18 +47,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
4747
// - initialize immediately with the given JSON datafile or its cached copy
4848
// - no network delay, but the local copy is not guaranteed to be in sync with the server experiment settings
4949

50-
//// initializeOptimizelySDKAsynchronous()
51-
//// initializeOptimizelySDKSynchronous()
52-
initializeOptimizelySDKWithCustomization()
53-
50+
initializeOptimizelySDKAsynchronous()
5451
}
5552

5653
// MARK: - Initialization Examples
5754

5855
func initializeOptimizelySDKAsynchronous() {
5956
optimizely = OptimizelyManager(sdkKey: sdkKey)
6057

61-
optimizely.initializeSDK { result in
58+
optimizely.startSDK { result in
6259
switch result {
6360
case .failure(let error):
6461
print("Optimizely SDK initiliazation failed: \(error)")
@@ -82,7 +79,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
8279

8380
do {
8481
let datafileJSON = try String(contentsOfFile: localDatafilePath, encoding: .utf8)
85-
try optimizely!.initializeSDK(datafile: datafileJSON)
82+
try optimizely!.startSDK(datafile: datafileJSON)
8683
print("Optimizely SDK initialized successfully!")
8784
} catch {
8885
print("Optimizely SDK initiliazation failed: \(error)")
@@ -96,6 +93,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
9693
// customization example (optional)
9794

9895
let customLogger = CustomLogger()
96+
// 30 sec interval may be too frequent. This is for demo purpose.
97+
// This should be should be much larger (default = 10 mins).
9998
let customDownloadIntervalInSecs = 30
10099

101100
optimizely = OptimizelyManager(sdkKey: sdkKey,
@@ -115,24 +114,27 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
115114
_ = optimizely.notificationCenter.addDatafileChangeNotificationListener(datafileListener: { (data) in
116115
DispatchQueue.main.async {
117116
#if os(iOS)
118-
let alert = UIAlertView(title: "Datafile change", message: "something changed.", delegate: nil, cancelButtonTitle: "cancel")
119-
alert.show()
117+
if let controller = self.window?.rootViewController {
118+
let alert = UIAlertController(title: "Datafile Changed", message: nil, preferredStyle: .alert)
119+
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default))
120+
controller.present(alert, animated: true)
121+
}
120122
#else
121123
print("Datafile changed")
122124
#endif
123-
}
124-
125-
if let controller = self.window?.rootViewController as? VariationViewController {
126-
//controller.showCoupon = toggle == FeatureFlagToggle.on ? true : false;
127-
if let showCoupon = try? self.optimizely.isFeatureEnabled(featureKey: "show_coupon", userId: self.userId) {
128-
controller.showCoupon = showCoupon
125+
126+
if let controller = self.window?.rootViewController as? VariationViewController {
127+
//controller.showCoupon = toggle == FeatureFlagToggle.on ? true : false;
128+
if let showCoupon = try? self.optimizely.isFeatureEnabled(featureKey: "show_coupon", userId: self.userId) {
129+
controller.showCoupon = showCoupon
130+
}
129131
}
130132
}
131133
})
132134

133135
// initialize SDK
134136

135-
optimizely!.initializeSDK { result in
137+
optimizely!.startSDK { result in
136138
switch result {
137139
case .failure(let error):
138140
print("Optimizely SDK initiliazation failed: \(error)")
@@ -201,7 +203,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
201203
}
202204

203205
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
204-
NotificationCenter.default.post(name: NSNotification.Name("OPTLYbackgroundFetchDone"), object: nil)
206+
207+
// add background fetch task here
208+
205209
completionHandler(.newData)
206210
}
207211
}

DemoSwiftApp/DemoSwiftiOS/Base.lproj/iOSMain.storyboard

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@
9898
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
9999
</imageView>
100100
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="A" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="GuL-M1-dn2">
101-
<rect key="frame" x="124" y="253" width="128" height="125"/>
101+
<rect key="frame" x="123.5" y="253" width="128" height="125"/>
102102
<constraints>
103103
<constraint firstAttribute="width" constant="128" id="RRZ-tK-QO5"/>
104104
</constraints>
@@ -107,7 +107,7 @@
107107
<nil key="highlightedColor"/>
108108
</label>
109109
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="VARIATION" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8CQ-8i-O97">
110-
<rect key="frame" x="128" y="368" width="120" height="24"/>
110+
<rect key="frame" x="127.5" y="368" width="120" height="24"/>
111111
<fontDescription key="fontDescription" name="ProximaNova-Regular" family="Proxima Nova" pointSize="24"/>
112112
<nil key="textColor"/>
113113
<nil key="highlightedColor"/>
@@ -146,6 +146,9 @@
146146
</constraints>
147147
<fontDescription key="fontDescription" type="system" pointSize="28"/>
148148
<state key="normal" title="Ok" backgroundImage="background_confirmation"/>
149+
<connections>
150+
<action selector="closeCoupon:" destination="Gt1-ok-FkN" eventType="touchUpInside" id="guX-ha-ev2"/>
151+
</connections>
149152
</button>
150153
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Coupon" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="wfb-0V-K6B">
151154
<rect key="frame" x="118" y="53" width="163" height="117"/>

DemoSwiftApp/VariationViewController.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ class VariationViewController: UIViewController {
3636
@IBOutlet weak var variationSubheaderLabel: UILabel!
3737
@IBOutlet weak var variationBackgroundImage: UIImageView!
3838

39+
@IBAction func closeCoupon(_ sender: UIButton) {
40+
showCoupon = false
41+
}
42+
3943
override func viewDidLoad() {
4044
super.viewDidLoad()
4145

OptimizelySDK/Customization/DefaultLogger.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ open class DefaultLogger : OPTLogger {
2020
private static var _logLevel: OptimizelyLogLevel?
2121
public static var logLevel: OptimizelyLogLevel {
2222
get {
23-
return _logLevel ?? .all
23+
return _logLevel ?? .info
2424
}
2525
set (newLevel){
2626
if _logLevel == nil {
@@ -30,7 +30,7 @@ open class DefaultLogger : OPTLogger {
3030
}
3131

3232
required public init() {
33-
DefaultLogger.logLevel = .all
33+
DefaultLogger.logLevel = .info
3434
}
3535

3636
open func log(level: OptimizelyLogLevel, message: String) {

OptimizelySDK/Optimizely/OptimizelyLogLevel.swift

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,26 @@ import Foundation
1212

1313
/// If the filter level is set to OptimizelyLogLevelOff, all log messages will be suppressed.
1414
case off = 0
15-
/// Any error that is causing a crash of the application.
16-
case critical = 1
1715
/// Any error that is not causing a crash of the application: unknown experiment referenced.
18-
case error = 2
16+
case error = 1
1917
/// Anything that can potentially cause problems: method will be deprecated.
20-
case warning = 3
18+
case warning = 2
2119
/// Useful information: Lifecycle events, successfully activated experiment, parsed datafile.
22-
case info = 4
20+
case info = 3
2321
/// Information diagnostically helpful: sending events, assigning buckets.
24-
case debug = 5
22+
case debug = 4
2523
/// Used for the most granular logging: method flows, variable values.
26-
case verbose = 6
27-
/// If the filter level is set to OptimizelyLogLevelAll, no log messages will be suppressed.
28-
case all = 7
24+
case verbose = 5
2925

3026
// NOTE: this property is not converted for ObjC APIs (separate map should be defined for ObjC-client customization)
3127
public var name: String {
3228
switch self {
3329
case .off: return "OFF"
34-
case .critical: return "CRITICAL"
3530
case .error: return "ERROR"
3631
case .warning: return "WARNING"
3732
case .info: return "INFO"
3833
case .debug: return "DEBUG"
3934
case .verbose: return "VERBOSE"
40-
case .all: return "ALL"
4135
}
4236
}
4337
}

OptimizelySDK/Optimizely/OptimizelyManager.swift

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -58,29 +58,33 @@ open class OptimizelyManager: NSObject {
5858
logger: OPTLogger? = nil,
5959
eventDispatcher: OPTEventDispatcher? = nil,
6060
userProfileService: OPTUserProfileService? = nil,
61-
periodicDownloadInterval: Int? = nil) {
61+
periodicDownloadInterval: Int? = nil,
62+
defaultLogLevel: OptimizelyLogLevel? = nil) {
6263

6364
self.sdkKey = sdkKey
6465
self.periodicDownloadInterval = periodicDownloadInterval ?? 10 * 60
6566

6667
super.init()
6768

6869
let userProfileService = userProfileService ?? DefaultUserProfileService()
70+
let logger = logger ?? DefaultLogger()
71+
type(of: logger).logLevel = defaultLogLevel ?? .info
72+
6973
self.registerServices(sdkKey: sdkKey,
70-
logger: logger ?? DefaultLogger(),
74+
logger: logger,
7175
eventDispatcher: eventDispatcher ?? DefaultEventDispatcher.sharedInstance,
7276
datafileHandler: DefaultDatafileHandler(),
7377
decisionService: DefaultDecisionService(userProfileService: userProfileService),
7478
notificationCenter: DefaultNotificationCenter())
7579

76-
logger?.i("SDK Version: \(Utils.getSDKVersion())")
80+
logger.i("SDK Version: \(Utils.getSDKVersion())")
7781
}
7882

7983
/// Initialize Optimizely Manager (Asynchronous)
8084
///
8185
/// - Parameters:
8286
/// - completion: callback when initialization is completed
83-
public func initializeSDK(resourceTimeout:Double? = nil,completion: ((OptimizelyResult<Data>) -> Void)?=nil) {
87+
public func startSDK(resourceTimeout:Double? = nil, completion: ((OptimizelyResult<Data>) -> Void)?=nil) {
8488
fetchDatafileBackground(resourceTimeout:resourceTimeout) { result in
8589
switch result {
8690
case .failure:
@@ -106,12 +110,12 @@ open class OptimizelyManager: NSObject {
106110
/// - datafile: when given, this datafile will be used when cached copy is not available (fresh start)
107111
/// a cached copy from previous download is used if it's available
108112
/// the datafile will be updated from the server in the background thread
109-
public func initializeSDK(datafile: String) throws {
113+
public func startSDK(datafile: String) throws {
110114
guard let datafileData = datafile.data(using: .utf8) else {
111115
throw OptimizelyError.dataFileInvalid
112116
}
113117

114-
try initializeSDK(datafile: datafileData)
118+
try startSDK(datafile: datafileData)
115119
}
116120

117121
/// Initialize Optimizely Manager (Synchronous)
@@ -123,7 +127,7 @@ open class OptimizelyManager: NSObject {
123127
/// - doFetchDatafileBackground: default to true. This is really here for debugging purposes when
124128
/// you don't want to download the datafile. In practice, you should allow the
125129
/// background thread to update the cache copy.
126-
public func initializeSDK(datafile: Data, doFetchDatafileBackground: Bool = true) throws {
130+
public func startSDK(datafile: Data, doFetchDatafileBackground: Bool = true) throws {
127131
let cachedDatafile = self.datafileHandler.loadSavedDatafile(sdkKey: self.sdkKey)
128132

129133
let selectedDatafile = cachedDatafile ?? datafile
@@ -717,7 +721,7 @@ extension OptimizelyManager {
717721
@available(swift, obsoleted: 1.0)
718722
@objc(initializeSDKWithCompletion:)
719723
public func _objcInitializeSDK(completion: ((Data?, NSError?) -> Void)?) {
720-
initializeSDK { result in
724+
startSDK { result in
721725
switch result {
722726
case .failure(let error):
723727
completion?(nil, self.convertErrorForObjc(error))
@@ -812,13 +816,13 @@ extension OptimizelyManager {
812816
@available(swift, obsoleted: 1.0)
813817
@objc(initializeSDKWithDatafile:error:)
814818
public func _objcInitializeSDKWith(datafile:String) throws {
815-
try self.initializeSDK(datafile: datafile)
819+
try self.startSDK(datafile: datafile)
816820
}
817821

818822
@available(swift, obsoleted: 1.0)
819823
@objc(initializeSDKWithDatafile:doFetchDatafileBackground:error:)
820824
public func _objcInitializeSDK(datafile: Data, doFetchDatafileBackground: Bool = true) throws {
821-
try self.initializeSDK(datafile: datafile, doFetchDatafileBackground: doFetchDatafileBackground)
825+
try self.startSDK(datafile: datafile, doFetchDatafileBackground: doFetchDatafileBackground)
822826
}
823827

824828
@available(swift, obsoleted: 1.0)

0 commit comments

Comments
 (0)