/
User.swift
executable file
·80 lines (66 loc) · 2.33 KB
/
User.swift
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
//
// User.swift
// Twitter
//
// Created by user on 2/18/16.
// Copyright © 2016 Aurielle. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCuurentUserKey";
let userDidLoginNotification = "userDidLoginNotification";
let userDidLogoutNotification = "userDidLogoutNotification";
class User: NSObject {
var name: String?
var screenname: String?
var profileImageUrl: String?
var tagline: String?
var dictionary: NSDictionary
init(dictionary: NSDictionary) {
self.dictionary = dictionary
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
profileImageUrl = dictionary["profile_image_url"] as? String
tagline = dictionary["description"] as? String
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
//logged out or just boot up
let data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
let dictionary: NSDictionary?
do {
try dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
_currentUser = User(dictionary: dictionary!)
} catch {
print(error)
}
}
}
return _currentUser
}
//please
set(user) {
_currentUser = user
//User need to implement NSCoding; but, JSON also serialized by default
if let _ = _currentUser {
var data: NSData?
do {
try data = NSJSONSerialization.dataWithJSONObject(user!.dictionary, options: .PrettyPrinted)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} catch {
print(error)
}
} else {
//Clear the currentUser data
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
}
}
}