我想爲我的應用程序構建一個分析類,並且我正在使用單例。在swift singleton中調用異步函數的正確方法
如果我運行這個,tagEvent函數立即運行而不是首先運行openSession(),所以sessionId返回nil。 如何通過適當的初始化創建一個像這樣的類,並像單例實例一樣使用它。
Analytics.swift
final class Analytics {
public static let instance = Analytics()
private var baseUrl = "http://localhost"
public var deviceId: String?
private init(){
self.deviceId = SomeFunctionGetsDeviceID()
}
func openSession(){
// make an API call to create a session and save sessionId to UserDefaults
if let url = URL(string: self.baseUrl + "/session"){
let params:[String:Any] = ["deviceId": "\(self.deviceId!)"]
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
AnalyticsSessionManager.sharedManager.request(request as URLRequestConvertible).validate().responseObject(completionHandler: { (response: DataResponse<SessionOpenResponse>) in
if response.result.value != nil {
UserDefaults.standard.set(response.result.value?.sessionId, forKey: "sessionId")
}
})
}
}
func closeSession(){
// make an API call to close a session and delete sessionId from UserDefaults
...
}
func tagEvent(eventName: String, attributes: [String : String]? = nil) {
if let url = URL(string: self.baseUrl + "/event"),
let sessionId = UserDefaults.standard.string(forKey: "sessionId"){
...
// make an API call to create an event with that sessionId
}
}
}
AppDelegate.swift
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Analytics.instance.openSession()
Analytics.instance.tagEvent(eventName: "App Launch", attributes:
["userID":"1234"])
}
'openSession'肯定是之前'tagEvent'調用。最可能的問題是'openSession'會立即返回,因爲它會進行異步調用。 – rmaddy
「進行API調用」實際上是什麼樣子? –
我編輯了一個API調用部分@rmaddy – invincible