forked from facebook/facebook-ios-sdk
/
FBLoginView.m
373 lines (314 loc) · 13.3 KB
/
FBLoginView.m
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBLoginView.h"
#import "FBProfilePictureView.h"
#import "FBRequest.h"
#import "FBRequestConnection+Internal.h"
#import "FBSession.h"
#import "FBGraphUser.h"
#import "FBUtility.h"
static NSString *const FBLoginViewCacheIdentity = @"FBLoginView";
const int kButtonLabelX = 46;
CGSize g_imageSize;
@interface FBLoginView() <UIActionSheetDelegate>
- (void)initialize;
- (void)buttonPressed:(id)sender;
- (void)configureViewForStateLoggedIn:(BOOL)isLoggedIn;
- (void)wireViewForSession:(FBSession *)session;
- (void)wireViewForSessionWithoutOpening:(FBSession *)session;
- (void)unwireViewForSession ;
- (void)fetchMeInfo;
- (void)informDelegate:(BOOL)userOnly;
- (void)handleActiveSessionSetNotifications:(NSNotification *)notification;
- (void)handleActiveSessionUnsetNotifications:(NSNotification *)notification;
@property (retain, nonatomic) UILabel *label;
@property (retain, nonatomic) UIButton *button;
@property (retain, nonatomic) FBSession *session;
@property (retain, nonatomic) FBRequestConnection *request;
@property (retain, nonatomic) id<FBGraphUser> user;
@end
@implementation FBLoginView
@synthesize delegate = _delegate,
label = _label,
button = _button,
session = _session,
request = _request,
user = _user,
permissions = _permissions;
- (id)init {
return [self initWithPermissions:nil];
}
- (id)initWithPermissions:(NSArray *)permissions {
self = [super init];
if (self) {
self.permissions = permissions;
[self initialize];
}
return self;
}
- (id)initWithFrame:(CGRect)aRect {
self = [super initWithFrame:aRect];
if (self) {
[self initialize];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self initialize];
}
return self;
}
- (void)dealloc {
// removes all observers for self
[[NSNotificationCenter defaultCenter] removeObserver:self];
// if we have an outstanding request, cancel
[self.request cancel];
[_request release];
[_label release];
[_button release];
[_session release];
[_user release];
[_permissions release];
[super dealloc];
}
- (void)setDelegate:(id<FBLoginViewDelegate>)newValue {
if (_delegate != newValue) {
_delegate = newValue;
// whenever the delegate value changes, we schedule one initial call to inform the delegate
// of our current state; we use a delay in order to avoid a callback in a setup or init method
[self performSelector:@selector(informDelegate:)
withObject:nil
afterDelay:.01];
}
}
- (void)initialize {
// the base class can cause virtual recursion, so
// to handle this we make initialize idempotent
if (self.button) {
return;
}
// setup view
self.autoresizesSubviews = YES;
self.clipsToBounds = YES;
// if our session has a cached token ready, we open it; note that it is important
// that we open the session before notification wiring is in place
[FBSession openActiveSessionWithPermissions:self.permissions
allowLoginUI:NO
completionHandler:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleActiveSessionSetNotifications:)
name:FBSessionDidSetActiveSessionNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleActiveSessionUnsetNotifications:)
name:FBSessionDidUnsetActiveSessionNotification
object:nil];
[self wireViewForSession:FBSession.activeSession];
// setup button
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.button addTarget:self
action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
self.button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UIImage *image = [[UIImage imageNamed:@"FacebookSDKResources.bundle/FBLoginView/images/login-button-small.png"]
stretchableImageWithLeftCapWidth:kButtonLabelX topCapHeight:0];
g_imageSize = image.size;
[self.button setBackgroundImage:image forState:UIControlStateNormal];
image = [[UIImage imageNamed:@"FacebookSDKResources.bundle/FBLoginView/images/login-button-small-pressed.png"]
stretchableImageWithLeftCapWidth:kButtonLabelX topCapHeight:0];
[self.button setBackgroundImage:image forState:UIControlStateHighlighted];
[self addSubview:self.button];
// add a label that will appear over the button
self.label = [[[UILabel alloc] init] autorelease];
self.label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.label.textAlignment = UITextAlignmentCenter;
self.label.backgroundColor = [UIColor clearColor];
self.label.font = [UIFont boldSystemFontOfSize:16.0];
self.label.textColor = [UIColor whiteColor];
self.label.shadowColor = [UIColor blackColor];
self.label.shadowOffset = CGSizeMake(0.0, -1.0);
[self addSubview:self.label];
// We force our height to be the same as the image, but we will let someone make us wider
// than the default image.
CGFloat width = MAX(self.frame.size.width, g_imageSize.width);
CGRect frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
width, image.size.height);
self.frame = frame;
CGRect buttonFrame = CGRectMake(0, 0, width, image.size.height);
self.button.frame = buttonFrame;
self.label.frame = CGRectMake(kButtonLabelX, 0, width - kButtonLabelX, image.size.height);
self.backgroundColor = [UIColor clearColor];
if (self.session.isOpen) {
[self fetchMeInfo];
[self configureViewForStateLoggedIn:YES];
} else {
[self configureViewForStateLoggedIn:NO];
}
}
- (CGSize)sizeThatFits:(CGSize)size {
CGSize logInSize = [[self logInText] sizeWithFont:self.label.font];
CGSize logOutSize = [[self logOutText] sizeWithFont:self.label.font];
// Leave at least a small margin around the label.
CGFloat desiredWidth = kButtonLabelX + 20 + MAX(logInSize.width, logOutSize.width);
// Never get smaller than the image
CGFloat width = MAX(desiredWidth, g_imageSize.width);
return CGSizeMake(width, g_imageSize.height);
}
- (NSString *)logInText {
return [FBUtility localizedStringForKey:@"FBLV:LogInButton" withDefault:@"Log In"];
}
- (NSString *)logOutText {
return [FBUtility localizedStringForKey:@"FBLV:LogOutButton" withDefault:@"Log Out"];
}
- (void)configureViewForStateLoggedIn:(BOOL)isLoggedIn {
if (isLoggedIn) {
self.label.text = [self logOutText];
} else {
self.label.text = [self logInText];
self.user = nil;
}
}
- (void)fetchMeInfo {
FBRequest *request = [FBRequest requestForMe];
[request setSession:self.session];
self.request = [[[FBRequestConnection alloc] init] autorelease];
[self.request addRequest:request
completionHandler:^(FBRequestConnection *connection, NSMutableDictionary<FBGraphUser> *result, NSError *error) {
if (result) {
self.user = result;
[self informDelegate:YES];
} else {
self.user = nil;
}
self.request = nil;
}];
[self.request startWithCacheIdentity:FBLoginViewCacheIdentity
skipRoundtripIfCached:YES];
}
- (void)informDelegate:(BOOL)userOnly {
if (userOnly) {
if ([self.delegate respondsToSelector:@selector(loginViewFetchedUserInfo:user:)]) {
[self.delegate loginViewFetchedUserInfo:self
user:self.user];
}
} else if (FBSession.activeSession.isOpen) {
if ([self.delegate respondsToSelector:@selector(loginViewShowingLoggedInUser:)]) {
[self.delegate loginViewShowingLoggedInUser:self];
}
// any time we inform/reinform of isOpen event, we want to be sure
// to repass the user if we have it
if (self.user) {
[self informDelegate:YES];
}
} else {
if ([self.delegate respondsToSelector:@selector(loginViewShowingLoggedOutUser:)]) {
[self.delegate loginViewShowingLoggedOutUser:self];
}
}
}
- (void)wireViewForSessionWithoutOpening:(FBSession *)session {
// if there is an outstanding request for the previous session, cancel
[self.request cancel];
self.request = nil;
self.session = session;
// register a KVO observer
[self.session addObserver:self
forKeyPath:@"state"
options:NSKeyValueObservingOptionNew
context:nil];
}
- (void)wireViewForSession:(FBSession *)session {
[self wireViewForSessionWithoutOpening:session];
// open the active session on the spot...
[FBSession openActiveSessionWithPermissions:self.permissions
allowLoginUI:NO // ... but only if a token is at the ready
completionHandler:nil];
}
- (void)unwireViewForSession {
// this line of code is the main reason we need to hold on
// to the session object at all
[self.session removeObserver:self
forKeyPath:@"state"];
self.session = nil;
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (self.session.isOpen) {
[self fetchMeInfo];
[self configureViewForStateLoggedIn:YES];
} else {
[self configureViewForStateLoggedIn:NO];
}
[self informDelegate:NO];
}
- (void)handleActiveSessionSetNotifications:(NSNotification *)notification {
// NSNotificationCenter is a global channel, so we guard against
// unexpected uses of this notification the best we can
if ([notification.object isKindOfClass:[FBSession class]]) {
[self wireViewForSession:notification.object];
}
}
- (void)handleActiveSessionUnsetNotifications:(NSNotification *)notification {
[self unwireViewForSession];
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) { // logout
[FBSession.activeSession closeAndClearTokenInformation];
}
}
- (void)buttonPressed:(id)sender {
if (self.session == FBSession.activeSession) {
if (!self.session.isOpen) { // login
[FBSession openActiveSessionWithPermissions:self.permissions
allowLoginUI:YES
completionHandler:nil];
} else { // logout action sheet
NSString *name = self.user.name;
NSString *title = nil;
if (name) {
title = [NSString stringWithFormat:[FBUtility localizedStringForKey:@"FBLV:LoggedInAs"
withDefault:@"Logged in as %@"], name];
} else {
title = [FBUtility localizedStringForKey:@"FBLV:LoggedInUsingFacebook"
withDefault:@"Logged in using Facebook"];
}
NSString *cancelTitle = [FBUtility localizedStringForKey:@"FBLV:CancelAction"
withDefault:@"Cancel"];
NSString *logOutTitle = [FBUtility localizedStringForKey:@"FBLV:LogOutAction"
withDefault:@"Log Out"];
UIActionSheet *sheet = [[[UIActionSheet alloc] initWithTitle:title
delegate:self
cancelButtonTitle:cancelTitle
destructiveButtonTitle:logOutTitle
otherButtonTitles:nil]
autorelease];
// Show the sheet
[sheet showInView:self];
}
} else { // state of view out of sync with active session
// so resync
[self unwireViewForSession];
[self wireViewForSession:FBSession.activeSession];
[self configureViewForStateLoggedIn:self.session.isOpen];
[self informDelegate:NO];
}
}
@end