forked from inaka/EventSource
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewController.swift
More file actions
88 lines (69 loc) · 2.51 KB
/
ViewController.swift
File metadata and controls
88 lines (69 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
// ViewController.swift
// EventSource
//
// Created by Andres on 2/13/15.
// Copyright (c) 2015 Inaka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet fileprivate weak var status: UILabel!
@IBOutlet fileprivate weak var dataLabel: UILabel!
@IBOutlet fileprivate weak var nameLabel: UILabel!
@IBOutlet fileprivate weak var idLabel: UILabel!
@IBOutlet fileprivate weak var squareConstraint: NSLayoutConstraint!
var eventSource: EventSource?
private let serverURL = URL(string: "http://127.0.0.1:8080/sse")!
private let headers = ["Authorization": "Bearer basic-auth-token"]
override func viewDidLoad() {
super.viewDidLoad()
eventSource = EventSource()
eventSource?.onOpen { [weak self] in
self?.status.backgroundColor = UIColor(red: 166/255, green: 226/255, blue: 46/255, alpha: 1)
self?.status.text = "CONNECTED"
}
eventSource?.onComplete { [weak self] statusCode, reconnect, error in
self?.status.backgroundColor = UIColor(red: 249/255, green: 38/255, blue: 114/255, alpha: 1)
self?.status.text = "DISCONNECTED"
guard reconnect ?? false else { return }
let retryTime = self?.eventSource?.retryTime ?? 3000
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(retryTime)) { [weak self] in
guard let self = self else { return }
self.eventSource?.connect(url: self.serverURL, headers: self.headers)
}
}
eventSource?.onMessage { [weak self] id, event, data in
self?.updateLabels(id, event: event, data: data)
}
eventSource?.addEventListener("user-connected") { [weak self] id, event, data in
self?.updateLabels(id, event: event, data: data)
}
}
func updateLabels(_ id: String?, event: String?, data: String?) {
idLabel.text = id
nameLabel.text = event
dataLabel.text = data
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let finalPosition = view.frame.size.width - 50
squareConstraint.constant = 0
view.layoutIfNeeded()
let animationOptions: UIView.KeyframeAnimationOptions = [
UIView.KeyframeAnimationOptions.repeat, UIView.KeyframeAnimationOptions.autoreverse
]
UIView.animateKeyframes(withDuration: 2,
delay: 0,
options: animationOptions,
animations: { () in
self.squareConstraint.constant = finalPosition
self.view.layoutIfNeeded()
}, completion: nil)
}
@IBAction func disconnect(_ sender: Any) {
eventSource?.disconnect()
}
@IBAction func connect(_ sender: Any) {
eventSource?.connect(url: serverURL, headers: headers)
}
}