CNLiveLoginViewController.m
21.7 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
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
//
// CNLiveLoginViewController.m
// CNLiveScioLive
//
// Created by Xiaowen Zhang on 2018/9/19.
// Copyright © 2018年 CNLive. All rights reserved.
//
#import "CNLiveLoginViewController.h"
#import "CNLiveRegisterViewController.h"
#import "CNLiveForgotPasswordViewController.h"
#import "CNLiveLoginInputView.h"
#import "CNLiveThirdLoginView.h"
#import "ZXWUserModel.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import <CNLiveRequestBastKit/CNLiveNetworking.h>
@interface CNLiveLoginViewController ()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
@property (nonatomic, strong) CNLiveLoginInputView *account;
@property (nonatomic, strong) CNLiveLoginInputView *pwd;
@end
@implementation CNLiveLoginViewController
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
if([User_Defaults objectForKey:@"user_phone"] && [User_Defaults objectForKey:@"user_phone"] != nil && ![[User_Defaults objectForKey:@"user_phone"] isEqualToString:@""]){
_account.textField.text = [User_Defaults objectForKey:@"user_phone"];
}else if([User_Defaults objectForKey:@"user_email"] && [User_Defaults objectForKey:@"user_email"] != nil && ![[User_Defaults objectForKey:@"user_email"] isEqualToString:@""]){
_account.textField.text = [User_Defaults objectForKey:@"user_email"];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setUpNavigationBar];
[self setUpSubControllers];
// Do any additional setup after loading the view.
}
#pragma mark - UI
- (void)setUpNavigationBar{
self.navigationController.navigationBar.barTintColor = Color_Blue;
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
//左
UIButton *headerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
headerButton.layer.cornerRadius = 2.0;
headerButton.layer.masksToBounds = true;
[headerButton setImage:[UIImage imageNamed:@"cnlive_white_back"] forState:UIControlStateNormal];
[headerButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headerButton];
self.navigationItem.title = CustomStr(@"Login");
}
- (void)setUpSubControllers{
_account = [[CNLiveLoginInputView alloc] initWithPic:@"cnlive_phone_email" placeholder:[NSString stringWithFormat:@"%@/%@", CustomStr(@"PhoneNumber"), CustomStr(@"Email")] type:CNLiveButtonTypeNormal];
[self.view addSubview:_account];
[_account mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top).with.offset(15);
make.left.equalTo(self.view.mas_left).with.offset(0);
make.right.equalTo(self.view.mas_right).with.offset(0);
make.height.offset(40);
}];
_pwd = [[CNLiveLoginInputView alloc] initWithPic:@"cnlive_password" placeholder:CustomStr(@"Password") type:CNLiveButtonTypeTextEntry];
[self.view addSubview:_pwd];
[_pwd mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self->_account.mas_bottom).with.offset(15);
make.left.equalTo(self.view.mas_left).with.offset(0);
make.right.equalTo(self.view.mas_right).with.offset(0);
make.height.offset(40);
}];
UIButton *loginButton = [[UIButton alloc] init];
loginButton.tag = 10000;
loginButton.layer.cornerRadius = 5.0;
loginButton.layer.masksToBounds = true;
[loginButton addTarget:self action:@selector(clicekdButton:) forControlEvents:UIControlEventTouchUpInside];
[loginButton setTitle:CustomStr(@"Login") forState:UIControlStateNormal];
[loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
loginButton.titleLabel.font = [UIFont systemFontOfSize:17];
loginButton.backgroundColor = Color_Blue;
[self.view addSubview:loginButton];
[loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self->_pwd.mas_bottom).with.offset(20);
make.left.equalTo(self.view.mas_left).with.offset(10);
make.right.equalTo(self.view.mas_right).with.offset(-10);
make.height.offset(40);
}];
UIButton *registerButton = [[UIButton alloc] init];
registerButton.tag = 10001;
registerButton.layer.cornerRadius = 2.0;
registerButton.layer.masksToBounds = true;
[registerButton addTarget:self action:@selector(clicekdButton:) forControlEvents:UIControlEventTouchUpInside];
[registerButton setTitle:CustomStr(@"SignUp") forState:UIControlStateNormal];
[registerButton setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
registerButton.titleLabel.font = [UIFont systemFontOfSize:14];
[self.view addSubview:registerButton];
[registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(loginButton.mas_left).with.offset(0);
make.top.equalTo(loginButton.mas_bottom).with.offset(15);
make.width.offset(120);
make.height.offset(25);
}];
UIButton *pwdButton = [[UIButton alloc] init];
pwdButton.tag = 10002;
[pwdButton addTarget:self action:@selector(clicekdButton:) forControlEvents:UIControlEventTouchUpInside];
[pwdButton setTitle:CustomStr(@"ForgotPassword") forState:UIControlStateNormal];
[pwdButton setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
pwdButton.titleLabel.font = [UIFont systemFontOfSize:14];
[self.view addSubview:pwdButton];
[pwdButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(loginButton.mas_right).with.offset(0);
make.top.equalTo(loginButton.mas_bottom).with.offset(15);
make.width.offset(120);
make.height.offset(25);
}];
NSArray *pics = @[@"cnlive_wechat", @"cnlive_qq", @"cnlive_weibo"];
CNLiveThirdLoginView *thirdLoginView = [[CNLiveThirdLoginView alloc]initWithFrame:CGRectMake(0, MainScreenHeight-100-NavBarContentHeight-TabBarHeight, MainScreenWidth, 100)];
thirdLoginView.btns = pics;
thirdLoginView.block = ^(NSInteger tag) {
[self loginThirdParty:tag];
};
[self.view addSubview:thirdLoginView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark - Action
- (void)allResignFirstResponder{
[_account.textField resignFirstResponder];
[_pwd.textField resignFirstResponder];
}
- (void)sendLoginRequest:(UIButton *)btn{
[self allResignFirstResponder];
NSRange range = [_account.textField.text rangeOfString:@"@"];
if(range.location == NSNotFound) {
if (![_account.textField.text isValidMobile]) {
[AlertViewTool showHUDViewText:CustomStr(@"PhoneNumberError")];
btn.userInteractionEnabled = YES;
return;
}
} else {
if (![_account.textField.text isValidEmail]) {
[AlertViewTool showHUDViewText:CustomStr(@"EmailError")];
return;
}
}
if(![_pwd.textField.text isValidPassWordLegal]){
[AlertViewTool showHUDViewText:CustomStr(@"PasswordError")];
btn.userInteractionEnabled = YES;
return;
}
#pragma mark - CNLiveUserSystemSDK 登录
if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
[AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
btn.userInteractionEnabled = YES;
return;
}
[AlertViewTool showHUDView];
[CNLiveUserSystemCenter loginWithUserName:_account.textField.text password:_pwd.textField.text frmId:nil success:^(NSDictionary *result) {
[AlertViewTool hideHUDView];
if ([result[@"errorCode"] integerValue] == 0) {
ZXWUserInformation *share = [ZXWUserInformation shareZXWUserInformation];
share.model = [[ZXWUserModel alloc] initWithDictionary:result[@"data"]];
[[ZXWUserInformation shareZXWUserInformation] saveToken:@""];
[[ZXWUserInformation shareZXWUserInformation] saveUser_id:@""];
[[ZXWUserInformation shareZXWUserInformation] setIsLoginSuccess:YES];
[[ZXWUserInformation shareZXWUserInformation] saveUser_name:result[@"data"][@"nickName"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_pwd:self->_pwd.textField.text];
[[ZXWUserInformation shareZXWUserInformation] saveUser_phone:result[@"data"][@"mobile"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_email:result[@"data"][@"email"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_headimgUrlString:result[@"data"][@"faceUrl"]];
[[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessful object:nil];
[AlertViewTool showHUDViewText:CustomStr(@"LoginSuccess") block:^{
btn.userInteractionEnabled = YES;
[self goBack];
}];
} else {
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
btn.userInteractionEnabled = YES;
}
} failure:^(NSDictionary *errorDic) {
[AlertViewTool hideHUDView];
[AlertViewTool showHUDViewText:errorDic[@"errorMessage"]];
btn.userInteractionEnabled = YES;
}];
}
- (void)clicekdButton:(UIButton *)btn{
switch (btn.tag) {
case 10000:
{
btn.userInteractionEnabled = NO;
[self sendLoginRequest:btn];
}
break;
case 10001:
{
CNLiveRegisterViewController *vc = [CNLiveRegisterViewController new];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc animated:YES];
}
break;
case 10002:
{
//忘记密码
//http://my.cnlive.com/cnlive_ucloud/static/yhcloud/verifyMode.html?appId=38_ivkou3xi05
CNLiveWebViewController *vc = [CNLiveWebViewController new];
vc.navTitle = CustomStr(@"ResetPassword");
vc.url = [NSString stringWithFormat:@"http://my.cnlive.com/cnlive_ucloud/static/yhcloud/verifyMode.html?appId=%@",CNLiveAppId];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc animated:YES];
}
break;
default:
break;
}
}
- (void)loginThirdParty:(NSInteger)tag {
#pragma mark - CNLiveUserSystemSDK 第三方登录
if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
[AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
return;
}
// 平台类型
SSDKPlatformType type = SSDKPlatformTypeUnknown;
NSString *plat = @"";
switch (tag) {
case 1000:
type = SSDKPlatformTypeWechat;
plat = @"3";
break;
case 1001:
type = SSDKPlatformTypeQQ;
plat = @"2";
break;
case 1002:
type = SSDKPlatformTypeSinaWeibo;
plat = @"1";
break;
case 1003: //苹果登录
if (@available(iOS 13.0, *)) {
[self networkParamAction];
[self signInWithApple];
}
return;
break;
default:
break;
}
[ShareSDK getUserInfo:type onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
switch (state) {
case SSDKResponseStateSuccess: {
// 准备登录参数
[CNLiveUserSystemCenter thirdPartyLoginWithThirdPartyPlatType:plat thirdPartyId:user.uid nickName:user.nickname gender:nil location:nil faceUrl:user.icon frmId:nil success:^(NSDictionary *result) {
if ([result[@"errorCode"] integerValue] == 0) {
[self saveUserInfo:result];
} else {
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
}
} failure:^(NSDictionary *errorDic) {
[AlertViewTool showHUDViewText:errorDic[@"errorMessage"]];
}];
break;
}
case SSDKResponseStateFail:
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
case SSDKResponseStateCancel:
[AlertViewTool showHUDViewText:CustomStr(@"CancelLogin")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
default:{
}
break;
}
}];
}
- (void)saveUserInfo:(NSDictionary *)result{
ZXWUserInformation *share = [ZXWUserInformation shareZXWUserInformation];
share.model = [[ZXWUserModel alloc] initWithDictionary:result[@"data"]];
[[ZXWUserInformation shareZXWUserInformation] saveToken:result[@"data"][@"token"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_id:@""];
[[ZXWUserInformation shareZXWUserInformation] setIsLoginSuccess:YES];
[[ZXWUserInformation shareZXWUserInformation] saveUser_name:result[@"data"][@"nickName"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_pwd:self->_pwd.textField.text];
[[ZXWUserInformation shareZXWUserInformation] saveUser_phone:result[@"data"][@"mobile"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_email:result[@"data"][@"email"]];
[[ZXWUserInformation shareZXWUserInformation] saveUser_headimgUrlString:result[@"data"][@"faceUrl"]];
[[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessful object:nil];
[AlertViewTool showHUDViewText:CustomStr(@"LoginSuccess") block:^{
[self goBack];
}];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self allResignFirstResponder];
}
- (void)signInWithApple API_AVAILABLE(ios(13.0)) {
ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
ASAuthorizationAppleIDRequest *request = [provider createRequest];
request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
ASAuthorizationController *vc = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
vc.delegate = self;
vc.presentationContextProvider = self;
[vc performRequests];
}
#pragma mark - ASAuthorizationControllerDelegate
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
NSString *state = credential.state;
NSString *userID = credential.user;
NSPersonNameComponents *fullName = credential.fullName;
NSString *email = credential.email;
NSString *authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding]; // refresh token
NSString *identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding]; // access token
ASUserDetectionStatus realUserStatus = credential.realUserStatus;
// NSLog(@"state: %@", state);
// NSLog(@"userID: %@", userID);
// NSLog(@"fullName: %@", fullName);
// NSLog(@"email: %@", email);
// NSLog(@"authorizationCode: %@", authorizationCode);
// NSLog(@"identityToken: %@", identityToken);
// NSLog(@"realUserStatus: %@", @(realUserStatus));
NSArray * subKeys = [NSArray arrayWithObjects:@"code",@"token",@"userId", @"appId", nil];
NSArray * subValues = [NSArray arrayWithObjects:authorizationCode, identityToken, userID, CNLiveAppId, nil];
NSDictionary * dic = [[NSDictionary alloc] initWithObjects:subValues forKeys:subKeys];
[CNLiveNetworking setupShowResult:NO];
[CNLiveNetworking setupShowDataResult:NO];
[CNLiveNetworking setAllowRequestDefaultArgument:YES];
[CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:@"https://api.cnlive.com/open/api2/user/verifyAppleToken" Param:dic CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
if (!error) {
NSDictionary *params = @{@"thirdPartyPlat":@"5",
@"thirdPartyId":userID?userID:@"",
@"frmId":@"",
@"clientPlat":@"i",
@"nickName":fullName.familyName?fullName.familyName:@"",
@"gender":@"",
@"location":@"",
@"faceUrl":@"",
@"appId":CNLiveAppId};
__weak typeof(self) weakSelf = self;
[CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:@"https://api.cnlive.com/open/api2/user/loginIn3rdForWJJApple" Param:params CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if(!strongSelf) return;
if ([responseObject isKindOfClass:[NSDictionary class]] && [responseObject[@"errorCode"] isEqualToString:@"0"]) {
[self saveUserInfo:responseObject];
} else {
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure") block:^{}];
}
}];
}
}];
}
}
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
NSString *errorMsg = nil;
switch (error.code) {
case ASAuthorizationErrorCanceled:
errorMsg = @"用户取消了授权请求";
[AlertViewTool showHUDViewText:CustomStr(@"CancelLogin")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
case ASAuthorizationErrorFailed:
errorMsg = @"授权请求失败";
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
case ASAuthorizationErrorInvalidResponse:
errorMsg = @"授权请求响应无效";
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
case ASAuthorizationErrorNotHandled:
errorMsg = @"未能处理授权请求";
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
case ASAuthorizationErrorUnknown:
errorMsg = @"授权请求失败未知原因";
[AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[AlertViewTool hideHUDView];
});
break;
}
NSLog(@"%@", errorMsg);
}
#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)) {
return self.view.window;
}
- (void)networkParamAction {
NSMutableDictionary * mDict = [[NSMutableDictionary alloc] init];
[mDict setValue:@"" forKey:@"loginSid"];
[mDict setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"] forKey:@"platform_id"];
[mDict setValue:@"i" forKey:@"plat"];
[mDict setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"ver"];
[mDict setObject:CNLiveAppId forKey:@"appId"];
[mDict setValue:[[[[UIDevice currentDevice] identifierForVendor] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""] forKey:@"uuid"];
[CNLiveNetworking setupDefaultParam:mDict];
[CNLiveNetworking setupShowResult:NO];
[CNLiveNetworking setupSignKey:CNLiveAppKey];
[CNLiveNetworking setAllowRequestDefaultArgument:YES];
[CNLiveNetworking setResponseSerializerType:CNLiveResponseSerializerJSON];
}
@end