565 lines
22 KiB
Objective-C
565 lines
22 KiB
Objective-C
//
|
|
// LogInViewController.m
|
|
// Ifish
|
|
//
|
|
// Created by imac on 15/9/28.
|
|
// Copyright © 2015年 imac. All rights reserved.
|
|
//
|
|
|
|
#import "LogInViewController.h"
|
|
//#import "JPUSHService.h"
|
|
#import "ForgetViewController.h"
|
|
#import "CenterViewController.h"
|
|
#import "LeftViewController.h"
|
|
#import "RightViewController.h"
|
|
#import "AFNetworking.h"
|
|
#import "ICSDrawerController.h"
|
|
#import "AppDelegate.h"
|
|
#import "UserModel.h"
|
|
#import "DataCenter.h"
|
|
#import "ConnectWifiViewController.h"
|
|
#import "MyMD5.h"
|
|
#import "RegistViewController.h"
|
|
|
|
#import "PuasiphysicalSkinViewController.h"
|
|
#import "IfishBlackListCenterViewController.h"
|
|
//#import <RongIMKit/RongIMKit.h>
|
|
//#import <RongIMLib/RongIMLib.h>
|
|
//#import "FirstConnectWifiController.h"
|
|
//#import "SelectDeviceViewController.h"
|
|
|
|
#import "IfishDataUnity.h"
|
|
#import "NetManager.h"
|
|
#import "UDManager.h"
|
|
#import "AccountResult.h"
|
|
#import "LoginResult.h"
|
|
#import "RegisterResult.h"
|
|
|
|
#import "UIView+Toast.h"
|
|
#import "IfishNewsModel.h"
|
|
//#import <BaiduMapAPI_Location/BMKLocationService.h>
|
|
//#import <BaiduMapAPI_Search/BMKSearchComponent.h>
|
|
//#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
|
|
#import <CoreLocation/CoreLocation.h>
|
|
#import "IfishUserDataUnity.h"
|
|
@interface LogInViewController ()<UITextFieldDelegate,CLLocationManagerDelegate>
|
|
@property (weak, nonatomic) IBOutlet UIButton *logInButton;
|
|
@property(nonatomic,strong)UIActivityIndicatorView*indicatorView;
|
|
//@property(nonatomic)BMKLocationService*locService;
|
|
@property(nonatomic) double longitude;
|
|
@property(nonatomic) double latitude;
|
|
@property(nonatomic,copy) NSString *adderss;
|
|
@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
|
|
@property (nonatomic,copy) NSString *currentCity;//城市
|
|
@end
|
|
extern BOOL firstLogIn;
|
|
BOOL formLogIn;// //连接页面是否来自登录界面初始化
|
|
|
|
@implementation LogInViewController
|
|
|
|
- (void)viewDidLoad {
|
|
[super viewDidLoad];
|
|
|
|
self.view.backgroundColor= [UIColor colorWithPatternImage:[UIImage imageNamed:@"enter_background"]];
|
|
|
|
[self getLocation];
|
|
_logInButton.backgroundColor=COLOR_LABEL_TITLE;
|
|
_logInButton.layer.cornerRadius = 5;
|
|
|
|
[self.loginPhoneNumberTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
|
|
[self.loginPasswordTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
|
|
|
|
[self.wangJiBtn addTarget:self action:@selector(forgetPassword:) forControlEvents:UIControlEventTouchUpInside];
|
|
[self.wangJiBtn setTitleColor:[UIColor colorWithRed:146/255.0f green:146/255.0f blue:146/255.0f alpha:1] forState:UIControlStateNormal];
|
|
|
|
|
|
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
|
|
self.deviceArry=[[NSMutableArray alloc] init];
|
|
|
|
self.cameraArr = [[NSMutableArray alloc] init];
|
|
self.loginPasswordTextField.delegate=self;
|
|
self.loginPhoneNumberTextField.delegate=self;
|
|
UILabel*labe=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
|
|
labe.text=@"登录";
|
|
labe.textAlignment=NSTextAlignmentCenter;
|
|
labe.textColor=[UIColor whiteColor];
|
|
self.navigationItem.titleView=labe;
|
|
|
|
self.navigationItem.hidesBackButton=YES;
|
|
|
|
UIBarButtonItem*rightItem= [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStyleDone target:self action:@selector(backItemBtn)];
|
|
|
|
|
|
self.navigationItem.rightBarButtonItem= rightItem;
|
|
[self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],UITextAttributeFont, [UIColor whiteColor], UITextAttributeTextColor, nil] forState:UIControlStateNormal];
|
|
|
|
|
|
[self initTextViewImg];
|
|
|
|
//self.view.backgroundColor=COLOR_MIAN;
|
|
|
|
[self setTextkeyboadType];
|
|
self.bakbutton.hidden=YES;
|
|
[self creatMyindicaterView];
|
|
formLogIn=YES;
|
|
|
|
NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults];
|
|
NSString *name=[userdefult objectForKey:@"name"];
|
|
if (name) {
|
|
self.loginPhoneNumberTextField.text = name;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#pragma mark 定位
|
|
-(void)getLocation{
|
|
//初始化BMKLocationService
|
|
|
|
if ([CLLocationManager locationServicesEnabled]) {
|
|
_locationManager = [[CLLocationManager alloc]init];
|
|
_locationManager.delegate = self;
|
|
[_locationManager requestAlwaysAuthorization];
|
|
_currentCity = [[NSString alloc]init];
|
|
[_locationManager requestWhenInUseAuthorization];
|
|
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
|
|
_locationManager.distanceFilter = 5.0;
|
|
[_locationManager startUpdatingLocation];
|
|
}
|
|
|
|
|
|
}
|
|
|
|
-(void)viewWillAppear:(BOOL)animated{
|
|
// _geocodesearch.delegate=self;// 此处记得不用的时候需要置nil,否则影响内存的释放
|
|
// _locService.delegate=self;
|
|
if ([CLLocationManager locationServicesEnabled]) {
|
|
_locationManager = [[CLLocationManager alloc]init];
|
|
_locationManager.delegate = self;
|
|
[_locationManager requestAlwaysAuthorization];
|
|
// _currentCity = [[NSString alloc]init];
|
|
[_locationManager requestWhenInUseAuthorization];
|
|
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
|
|
_locationManager.distanceFilter = 5.0;
|
|
[_locationManager startUpdatingLocation];
|
|
}
|
|
|
|
}
|
|
|
|
-(void)viewWillDisappear:(BOOL)animated{
|
|
|
|
// _locService.delegate=nil;
|
|
}
|
|
|
|
-(void)backItemBtn{
|
|
if (firstLogIn==YES) {
|
|
[self.navigationController popToRootViewControllerAnimated:YES];
|
|
}else{
|
|
RegistViewController*regist=[[RegistViewController alloc]init];
|
|
|
|
[self.navigationController pushViewController:regist animated:YES];
|
|
|
|
|
|
}
|
|
// [self.navigationController popViewControllerAnimated:YES];
|
|
|
|
}
|
|
|
|
-(void)creatMyindicaterView{
|
|
_indicatorView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
|
|
|
|
_indicatorView.frame=CGRectMake(kScreenSize.width/2-20,kScreenSize.height/2-20,40, 40);
|
|
|
|
[self.view addSubview:_indicatorView];
|
|
|
|
}
|
|
|
|
-(void)setTextkeyboadType{
|
|
// self.phoneNumberTextField.keyboardType=UIKeyboardTypeNumberPad;
|
|
self.loginPasswordTextField.secureTextEntry=YES;
|
|
}
|
|
-(void)initTextViewImg{
|
|
UIView*phoneView=[[UIView alloc]initWithFrame:CGRectMake(0,0, 50, 30)];
|
|
UIImageView*phoneIcon=[[UIImageView alloc]initWithFrame:CGRectMake(15,5, 17,20)];
|
|
|
|
phoneIcon.image=[UIImage imageNamed:@"phone"];
|
|
[phoneView addSubview:phoneIcon];
|
|
self.loginPhoneNumberTextField.leftView=phoneView;
|
|
self.loginPhoneNumberTextField.leftViewMode=UITextFieldViewModeAlways;
|
|
self.loginPhoneNumberTextField.layer.cornerRadius=6;
|
|
[self.loginPhoneNumberTextField setValue:[UIColor colorWithRed:146.0/255.0 green:146.0/255.0 blue:146.0/255.0 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
|
|
|
|
UIView*passView=[[UIView alloc]initWithFrame:CGRectMake(0,30, 50, 30)];
|
|
UIImageView*passIcon=[[UIImageView alloc]initWithFrame:CGRectMake(15,5, 17, 20)];
|
|
passIcon.image=[UIImage imageNamed:@"password"];
|
|
[passView addSubview:passIcon];
|
|
self.loginPasswordTextField.leftView=passView;
|
|
self.loginPasswordTextField.leftViewMode=UITextFieldViewModeAlways;
|
|
self.loginPasswordTextField.layer.cornerRadius=6;
|
|
[self.loginPasswordTextField setValue:[UIColor colorWithRed:146.0/255.0 green:146.0/255.0 blue:146.0/255.0 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
|
|
// 设置用户头像
|
|
// int i = (arc4random()%11) + 1;// 设置随机头像
|
|
// self.userIconImg.image=[UIImage imageNamed:[NSString stringWithFormat:@"acount%d.png",i]];
|
|
//
|
|
|
|
|
|
}
|
|
|
|
#pragma mark-处理收键盘
|
|
|
|
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
|
|
[textField resignFirstResponder];
|
|
|
|
return YES;
|
|
|
|
}
|
|
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
|
|
[self hiddenKeybord];
|
|
|
|
}
|
|
|
|
-(void)hiddenKeybord{
|
|
|
|
[self.loginPhoneNumberTextField resignFirstResponder];
|
|
[self.loginPasswordTextField resignFirstResponder];
|
|
|
|
}
|
|
- (void)didReceiveMemoryWarning {
|
|
[super didReceiveMemoryWarning];
|
|
}
|
|
- (IBAction)LogIn:(id)sender {
|
|
|
|
//NSString * MOBILE = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
|
|
//包含港澳台
|
|
// BOOL isMacth=[dataContorl valiMobile:self.loginPhoneNumberTextField.text];
|
|
//
|
|
// if (!isMacth) {
|
|
// [self.view makeToast:@"请输入正确的手机号"];
|
|
// return;
|
|
// }
|
|
|
|
|
|
UIButton *btn = (UIButton *)sender;
|
|
btn.userInteractionEnabled = NO;
|
|
btn.backgroundColor = [UIColor lightGrayColor];
|
|
[_indicatorView startAnimating];
|
|
|
|
NSString*tokenStr=[MyMD5 md5:self.loginPasswordTextField.text ];
|
|
if (!self.adderss) {
|
|
NSLog(@"addressnil");
|
|
self.adderss = @"暂时未获取到地址信息";
|
|
}
|
|
if (!self.latitude) {
|
|
|
|
self.latitude = 0;
|
|
}
|
|
if (!self.longitude) {
|
|
|
|
self.longitude =0;
|
|
|
|
}
|
|
|
|
__weak typeof (self) weakSelf=self;
|
|
[AFHttpTool userLogInWithPhoneNumber:self.loginPhoneNumberTextField.text password:tokenStr phoneType:@"ios" address:self.adderss
|
|
longitude:self.longitude
|
|
latitude:self.latitude
|
|
success:^(id response) {
|
|
NSDictionary*dict=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
|
|
NSString *result=dict[@"result"];
|
|
btn.userInteractionEnabled = YES;
|
|
btn.backgroundColor = RGB(0, 184, 239);
|
|
if ([result isEqualToString:@"100"]) {
|
|
|
|
|
|
// 登录成功
|
|
NSDictionary*DataDic=dict[@"data"];
|
|
NSString*phoneNumber=self.loginPhoneNumberTextField.text;
|
|
NSString*password=self.loginPasswordTextField.text;
|
|
[[IfishUserDataUnity shareDataInstance] userloginValidationSuccsess:DataDic phoneNumber:phoneNumber passward:password];
|
|
//登陆成功之后,验证当前页面devicetoken是否上送成功,如果还未上送,则重新上送devicetoken
|
|
if (![[NSUserDefaults standardUserDefaults] boolForKey:is_Bind_DeviceToken]) {
|
|
UserModel *model=[[UserModel alloc] initWithDict:[DataDic objectForKey:@"userInfo"]];
|
|
NSDictionary *params = @{@"deviceId":[FuncUserDefault strForKey:kDeviceToken],
|
|
@"userId":model.userId,
|
|
@"phoneType":@"iOS"
|
|
};
|
|
[AFNOHeaderHttpTool requestWihtMethod:RequestTypePost url:Push_BindDevice_Url params:params success:^(id response) {
|
|
//绑定成功
|
|
[FuncUserDefault setBool:YES key:is_Bind_DeviceToken];//已经上送了本机的devicetoken
|
|
} failure:^(NSError *err) {
|
|
|
|
}];
|
|
}
|
|
}else if ([result isEqualToString:@"101"]){
|
|
|
|
[weakSelf.view makeToast:@"登录失败"];
|
|
//登录失败
|
|
}else if ([result isEqualToString:@"204"]){
|
|
// 验证失败,密码不正确
|
|
[weakSelf.view makeToast:@"验证失败,密码不正确"];
|
|
}else if ([result isEqualToString:@"202"]){
|
|
// 用户不存在
|
|
[weakSelf.view makeToast:@"用户不存在"];
|
|
}else if ([result isEqualToString:@"400"]){
|
|
// 用户不存在
|
|
|
|
[weakSelf.view makeToast:@"完全校验失败"];
|
|
}
|
|
[_indicatorView stopAnimating];
|
|
} failure:^(NSError *err) {
|
|
btn.userInteractionEnabled = YES;
|
|
btn.backgroundColor = RGB(0, 184, 239);
|
|
[_indicatorView stopAnimating];
|
|
[weakSelf.view makeToast:@"请求失败"];
|
|
NSString *errstr = [NSString stringWithFormat:@"%@",err];
|
|
BLYLog(BuglyLogLevelWarn, errstr);
|
|
|
|
}];
|
|
|
|
}
|
|
|
|
- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
|
|
|
|
NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
|
|
|
|
}
|
|
|
|
#pragma mark - 注册摄像头成功后 登陆摄像头服务器 已去
|
|
|
|
-(void)logInYooseeServerWith:(NSString*)email addpassword:(NSString*)password{
|
|
|
|
AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
|
|
NSString *token=appdelegate.token;
|
|
|
|
NSString *ifishEmial=[NSString stringWithFormat:@"ifish7%@@ifish7.com",self.loginPhoneNumberTextField.text];
|
|
|
|
// NSString *ifishPassW=[NSString stringWithFormat:@"ifish%@",userName];
|
|
NSString *ifishPassW=@"lian1030";
|
|
[[NetManager sharedManager] loginWithUserName:ifishEmial password:ifishPassW token: token callBack:^(id JSON) {
|
|
|
|
LoginResult *loginResult = (LoginResult*)JSON;
|
|
//登陆成功返回 LoginResult数据模型 存储
|
|
|
|
[UDManager setIsLogin:YES];
|
|
[UDManager setLoginInfo:loginResult];
|
|
|
|
|
|
NSLog(@"摄像头服务器成功登陆%@",JSON);
|
|
[[NetManager sharedManager] getAccountInfo:loginResult.contactId sessionId:loginResult.sessionId callBack:^(id JSN){
|
|
AccountResult *accountResult = (AccountResult*)JSN;
|
|
loginResult.email = accountResult.email;
|
|
loginResult.phone = accountResult.phone;
|
|
loginResult.countryCode = accountResult.countryCode;
|
|
[UDManager setLoginInfo:loginResult];
|
|
}];
|
|
//都登陆成功 跳主界面
|
|
|
|
|
|
}];
|
|
|
|
}
|
|
|
|
-(void)showTitle:(NSString*)title messsage:(NSString*)message{
|
|
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
|
|
[alert show];
|
|
}
|
|
|
|
- (IBAction)forgetPassword:(id)sender {
|
|
ForgetViewController*vc=[[ForgetViewController alloc]init];
|
|
[self.navigationController pushViewController:vc animated:YES];
|
|
}
|
|
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
|
|
|
|
{
|
|
|
|
// NSTimeInterval animationDuration=0.30f;
|
|
//
|
|
// [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
|
|
//
|
|
// [UIView setAnimationDuration:animationDuration];
|
|
|
|
if (textField == self.loginPhoneNumberTextField) {
|
|
|
|
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phonekeyboradWillShow:) name:UIKeyboardWillShowNotification object:nil];
|
|
|
|
}if (textField == self.loginPasswordTextField) {
|
|
|
|
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(passkeyboradWillShow:) name:UIKeyboardWillShowNotification object:nil];
|
|
|
|
}
|
|
|
|
return YES;
|
|
|
|
}
|
|
- (void) phonekeyboradWillShow:(NSNotification *)notification{
|
|
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
|
|
|
|
//计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
|
|
CGFloat offset = (_loginPhoneNumberTextField.frame.origin.y+_loginPhoneNumberTextField.frame.size.height+INTERVAL_KEYBOARD) - (self.view.frame.size.height - kbHeight);
|
|
|
|
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
|
|
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
|
|
|
|
//将视图上移计算好的偏移
|
|
if(offset > 0) {
|
|
[UIView animateWithDuration:duration animations:^{
|
|
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
|
|
}];
|
|
}
|
|
|
|
}
|
|
-(void)passkeyboradWillShow:(NSNotification *)notification{
|
|
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
|
|
CGFloat offset = (_loginPasswordTextField.frame.origin.y+_loginPasswordTextField.frame.size.height+INTERVAL_KEYBOARD) - (self.view.frame.size.height - kbHeight);
|
|
|
|
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
|
|
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
|
|
|
|
//将视图上移计算好的偏移
|
|
if(offset > 0) {
|
|
[UIView animateWithDuration:duration animations:^{
|
|
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
|
|
}];
|
|
}
|
|
|
|
|
|
}
|
|
|
|
//恢复原始视图位置
|
|
- (void) keyboardWillHide:(NSNotification *)notify {
|
|
// 键盘动画时间
|
|
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
|
|
|
|
//视图下沉恢复原状
|
|
[UIView animateWithDuration:duration animations:^{
|
|
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
|
|
}];
|
|
}
|
|
|
|
//处理方向变更信息
|
|
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
|
|
//{
|
|
// //NSLog(@"heading is %@",userLocation.heading);
|
|
//}
|
|
////处理位置坐标更新
|
|
//- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
|
|
//{
|
|
// NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
|
|
// self.latitude = userLocation.location.coordinate.latitude;
|
|
// self.longitude = userLocation.location.coordinate.longitude;
|
|
// static dispatch_once_t disOnce;
|
|
// dispatch_once(&disOnce, ^ {
|
|
//
|
|
// [self reverseGeoCodeWithlatitude:userLocation.location.coordinate.latitude addlongitude:userLocation.location.coordinate.longitude];
|
|
// });
|
|
//
|
|
//}
|
|
/**
|
|
* 地理反编码
|
|
*/
|
|
//-(void)reverseGeoCodeWithlatitude:(CLLocationDegrees)latitude addlongitude:(CLLocationDegrees)longitude{
|
|
// CLLocationCoordinate2D pt=(CLLocationCoordinate2D){latitude,longitude};
|
|
// BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
|
|
// reverseGeocodeSearchOption.reverseGeoPoint=pt;
|
|
// BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
|
|
// if(flag)
|
|
// {
|
|
// NSLog(@"反geo检索发送成功");
|
|
// }
|
|
// else
|
|
// {
|
|
// NSLog(@"反geo检索发送失败");
|
|
// }
|
|
//
|
|
//}
|
|
|
|
//-(void)dealloc{
|
|
//
|
|
// if (_geocodesearch!=nil) {
|
|
// _geocodesearch=nil;
|
|
// }
|
|
//}
|
|
|
|
#pragma mark BMKGeoCodeSearchDelegate
|
|
//-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
|
|
// NSLog(@"address%@",result.address);
|
|
//
|
|
// NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults];
|
|
// NSString*address=result.address;
|
|
// self.adderss = address;
|
|
// [userdefult setObject:address forKey:@"address"];
|
|
// [userdefult setDouble:self.latitude forKey:@"userlatitude"];
|
|
// [userdefult setDouble:self.longitude forKey:@"userlongitude"];
|
|
// [userdefult synchronize];
|
|
//
|
|
// _geocodesearch.delegate=nil;
|
|
//}
|
|
|
|
#pragma mark - 定位失败
|
|
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
|
|
|
|
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
|
|
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
|
|
NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
|
|
[[UIApplication sharedApplication]openURL:settingURL];
|
|
}];
|
|
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
|
|
|
|
}];
|
|
[alert addAction:cancel];
|
|
[alert addAction:ok];
|
|
[self presentViewController:alert animated:YES completion:nil];
|
|
}
|
|
#pragma mark - 定位成功
|
|
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
|
|
|
|
[_locationManager stopUpdatingLocation];
|
|
CLLocation *currentLocation = [locations lastObject];
|
|
CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
|
|
//当前的经纬度
|
|
NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
|
|
self.longitude=currentLocation.coordinate.longitude;
|
|
self.latitude=currentLocation.coordinate.latitude;
|
|
//这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
|
|
NSTimeInterval locationAge = -[currentLocation.timestamp timeIntervalSinceNow];
|
|
if (locationAge > 1.0){//如果调用已经一次,不再执行
|
|
return;
|
|
}
|
|
//地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
|
|
[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
|
|
if (placemarks.count >0) {
|
|
CLPlacemark *placeMark = placemarks[0];
|
|
_currentCity = placeMark.locality;
|
|
if (!_currentCity) {
|
|
_currentCity = @"无法定位当前城市";
|
|
}
|
|
//看需求定义一个全局变量来接收赋值
|
|
NSLog(@"当前国家 - %@",placeMark.country);//当前国家
|
|
NSLog(@"当前城市 - %@",_currentCity);//当前城市
|
|
NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
|
|
NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
|
|
NSLog(@"具体地址 - %@",placeMark.name);//具体地址
|
|
NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
|
|
NSUserDefaults*userdefult=[NSUserDefaults standardUserDefaults];
|
|
NSString*address=message;
|
|
self.adderss = address;
|
|
[userdefult setObject:address forKey:@"address"];
|
|
[userdefult setDouble:self.latitude forKey:@"userlatitude"];
|
|
[userdefult setDouble:self.longitude forKey:@"userlongitude"];
|
|
[userdefult synchronize];
|
|
|
|
}else if (error == nil && placemarks.count){
|
|
|
|
NSLog(@"NO location and error return");
|
|
}else if (error){
|
|
|
|
NSLog(@"loction error:%@",error);
|
|
}
|
|
}];
|
|
}
|
|
|
|
|
|
|
|
|
|
@end
|