/
FBLoginView.m
536 lines (457 loc) · 20.6 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/*
* Copyright 2010-present 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"
#import "FBSession+Internal.h"
#import "FBAppEvents+Internal.h"
#import "FBLoginViewButtonPNG.h"
#import "FBLoginViewButtonPressedPNG.h"
static NSString *const FBLoginViewCacheIdentity = @"FBLoginView";
// The design calls for 16 pixels of space on the right edge of the button
static const float kButtonEndCapWidth = 16.0;
// The button has a 12 pixel buffer to the right of the f logo
static const float kButtonPaddingWidth = 12.0;
static CGSize g_buttonSize;
// Forward declare our label wrapper that provides shadow blur
@interface FBShadowLabel : UILabel
@end
@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)informDelegateOfError:(NSError *)error;
- (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;
@property (copy, nonatomic) FBSessionStateHandler sessionStateHandler;
@property (copy, nonatomic) FBRequestHandler requestHandler;
// lastObservedStateWasOpen is essentially a nullable bool to track if the
// the session state was open when the inform delegate is called. This is
// to prevent messaging the delegate again in state transfers that are
// not important (e.g., tokenextended, or createdopening).
@property (copy) NSNumber *lastObservedStateWasOpen;
@end
@implementation FBLoginView
@synthesize delegate = _delegate,
label = _label,
button = _button,
session = _session,
request = _request,
user = _user,
permissions = _permissions,
readPermissions = _readPermissions,
publishPermissions = _publishPermissions,
defaultAudience = _defaultAudience,
lastObservedStateWasOpen = _lastObservedStateWasOpen,
sessionStateHandler = _sessionStateHandler,
requestHandler = _requestHandler;
- (id)init {
self = [super init];
if (self) {
[self initialize];
}
return self;
}
- (id)initWithPermissions:(NSArray *)permissions {
self = [super init];
if (self) {
self.permissions = permissions;
[self initialize];
}
return self;
}
- (id)initWithReadPermissions:(NSArray *)readPermissions {
self = [super init];
if (self) {
self.readPermissions = readPermissions;
[self initialize];
}
return self;
}
- (id)initWithPublishPermissions:(NSArray *)publishPermissions
defaultAudience:(FBSessionDefaultAudience)defaultAudience {
self = [super init];
if (self) {
self.publishPermissions = publishPermissions;
self.defaultAudience = defaultAudience;
[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 {
// As noted in `initializeBlocks`, if we are being dealloc'ed, we
// need to let our handlers know with the sentinel value of nil
// to prevent EXC_BAD_ACCESS errors.
self.sessionStateHandler(nil, FBSessionStateClosed, nil);
[_sessionStateHandler release];
[_requestHandler release];
// removes all observers for self
[[NSNotificationCenter defaultCenter] removeObserver:self];
// if we have an outstanding request, cancel
[self.request cancel];
// unwire the session to release KVO.
[self unwireViewForSession];
[_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)initializeBlocks {
// Set up our block handlers in a way that supports nil'ing out the weak self reference to
// prevent EXC_BAD_ACCESS errors if the session invokes the handler after the FBLoginView
// has been deallocated. Note the handlers are declared as a `copy` property so that
// the block lives on the heap.
__block FBLoginView *weakSelf = self;
self.sessionStateHandler = ^(FBSession *session, FBSessionState status, NSError *error) {
if (session == nil) {
// The nil sentinel value for session indicates both blocks should no-op thereafter.
weakSelf = nil;
} else if (error) {
[weakSelf informDelegateOfError:error];
}
};
self.requestHandler = ^(FBRequestConnection *connection, NSMutableDictionary<FBGraphUser> *result, NSError *error) {
if (result) {
weakSelf.user = result;
[weakSelf informDelegate:YES];
} else {
weakSelf.user = nil;
if (weakSelf.session.isOpen) {
// Only inform the delegate of errors if the session remains open;
// since session closure errors will surface through the openActiveSession
// block.
[weakSelf informDelegateOfError:error];
}
}
weakSelf.request = nil;
};
}
- (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;
[self initializeBlocks];
if ([FBSession activeSessionIfOpen] == nil) {
// 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 openActiveSessionWithReadPermissions:nil
allowLoginUI:NO
completionHandler:self.sessionStateHandler];
}
// wire-up the current session to the login view, before adding global session-change handlers
[self wireViewForSession:FBSession.activeSession];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleActiveSessionSetNotifications:)
name:FBSessionDidSetActiveSessionNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleActiveSessionUnsetNotifications:)
name:FBSessionDidUnsetActiveSessionNotification
object:nil];
// setup button
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.button addTarget:self
action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
self.button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// We want to make sure that when we stretch the image, it includes the curved edges and drop shadow
// We inset enough pixels to make sure that happens
UIEdgeInsets imageInsets = UIEdgeInsetsMake(4.0, 40.0, 4.0, 4.0);
UIImage *image = [[FBLoginViewButtonPNG image] resizableImageWithCapInsets:imageInsets];
[self.button setBackgroundImage:image forState:UIControlStateNormal];
image = [[FBLoginViewButtonPressedPNG image] resizableImageWithCapInsets:imageInsets];
[self.button setBackgroundImage:image forState:UIControlStateHighlighted];
[self addSubview:self.button];
// Compute the text size to figure out the overall size of the button
UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0];
float textSizeWidth = MAX([[self logInText] sizeWithFont:font].width, [[self logOutText] sizeWithFont:font].width);
// We make the button big enough to hold the image, the text, the padding to the right of the f and the end cap
g_buttonSize = CGSizeMake(image.size.width + textSizeWidth + kButtonPaddingWidth + kButtonEndCapWidth, image.size.height);
// add a label that will appear over the button
self.label = [[[FBShadowLabel alloc] init] autorelease];
self.label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.label.textAlignment = UITextAlignmentCenter;
self.label.backgroundColor = [UIColor clearColor];
self.label.font = font;
self.label.textColor = [UIColor whiteColor];
[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_buttonSize.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;
// This needs to start at an x just to the right of the f in the image, the -1 on both x and y is to account for shadow in the image
self.label.frame = CGRectMake(image.size.width - kButtonPaddingWidth - 1, -1, width - (image.size.width - kButtonPaddingWidth) - kButtonEndCapWidth, image.size.height);
self.backgroundColor = [UIColor clearColor];
if (self.session.isOpen) {
[self fetchMeInfo];
[self configureViewForStateLoggedIn:YES];
} else {
[self configureViewForStateLoggedIn:NO];
}
}
- (CGSize)sizeThatFits:(CGSize)size {
return CGSizeMake(g_buttonSize.width, g_buttonSize.height);
}
- (NSString *)logInText {
return [FBUtility localizedStringForKey:@"FBLV:LogInButton" withDefault:@"Log in with Facebook"];
}
- (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:self.requestHandler];
[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.lastObservedStateWasOpen isEqualToNumber:@1]) {
self.lastObservedStateWasOpen = @1;
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.lastObservedStateWasOpen isEqualToNumber:@0]) {
self.lastObservedStateWasOpen = @0;
if ([self.delegate respondsToSelector:@selector(loginViewShowingLoggedOutUser:)]) {
[self.delegate loginViewShowingLoggedOutUser:self];
}
}
}
}
- (void)informDelegateOfError:(NSError *)error {
if (error) {
if ([self.delegate respondsToSelector:@selector(loginView:handleError:)]) {
[self.delegate loginView:self
handleError:error];
}
}
}
- (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];
// anytime we find that our session is created with an available token
// we open it on the spot
if (self.session.state == FBSessionStateCreatedTokenLoaded) {
[self.session openWithBehavior:FBSessionLoginBehaviorUseSystemAccountIfPresent
completionHandler:self.sessionStateHandler];
}
}
- (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];
}
}
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
- (void)buttonPressed:(id)sender {
if (self.session == FBSession.activeSession) {
BOOL loggingInLogFlag = NO;
if (!self.session.isOpen) { // login
// the policy here is:
// 1) if you provide unspecified permissions, then we fall back on legacy fast-app-switch
// 2) if you provide only read permissions, then we call a read-based open method that will use integrated auth
// 3) if you provide any publish permissions, then we combine the read-set and publish-set and call the publish-based
// method that will use integrated auth when availab le
// 4) if you provide any publish permissions, and don't specify a valid audience, the control will throw an exception
// when the user presses login
if (self.permissions) {
[FBSession openActiveSessionWithPermissions:self.permissions
allowLoginUI:YES
defaultAudience:self.defaultAudience
completionHandler:self.sessionStateHandler];
} else if (![self.publishPermissions count]) {
[FBSession openActiveSessionWithReadPermissions:self.readPermissions
allowLoginUI:YES
completionHandler:self.sessionStateHandler];
} else {
// combined read and publish permissions will usually fail, but if the app wants us to
// try it here, then we will pass the aggregate set to the server
NSArray *permissions = self.publishPermissions;
if ([self.readPermissions count]) {
NSMutableSet *set = [NSMutableSet setWithArray:self.publishPermissions];
[set addObjectsFromArray:self.readPermissions];
permissions = [set allObjects];
}
[FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:self.defaultAudience
allowLoginUI:YES
completionHandler:self.sessionStateHandler];
}
loggingInLogFlag = YES;
} 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];
}
[FBAppEvents logImplicitEvent:FBAppEventNameLoginViewUsage
valueToSum:nil
parameters:@{ @"logging_in" : [NSNumber numberWithBool:loggingInLogFlag] }
session:nil];
} 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];
}
}
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
@end
@implementation FBShadowLabel
- (void) drawTextInRect:(CGRect)rect {
CGSize myShadowOffset = CGSizeMake(0, -1);
float myColorValues[] = {0, 0, 0, .3};
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(myContext);
CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef myColor = CGColorCreate(myColorSpace, myColorValues);
CGContextSetShadowWithColor (myContext, myShadowOffset, 1, myColor);
[super drawTextInRect:rect];
CGColorRelease(myColor);
CGColorSpaceRelease(myColorSpace);
CGContextRestoreGState(myContext);}
@end