В моем приложении есть две роли: покупатели и продавцы, и есть соответствующие контроллеры просмотра: BuyerViewController и SellerViewController. Роль по умолчанию - покупатель, но можно зарегистрироваться и стать продавцом в меню. Когда приложение запускается, появляется BuyerViewController. Покупатель начинает торговлю с продавцом онлайн. Когда начинается торговля, покупатель видит профиль продавца в BuyerViewController, и продавец видит информацию о профиле покупателя в SalesViewController. Приложение работает идеально на переднем плане.Вид исчезает, и первый диспетчер представлений возобновляется, когда приложение работает в фоновом режиме
Однако, когда телефоны остаются закрытыми, как 2-3 минуты, и когда я возвращаюсь к приложениям, оба экрана открывают BuyerViewController. Взгляд покупателя очищается: профиль продавца исчезает в телефоне покупателей, и SellerViewController полностью исчезает. В основном оба телефона возвращаются в исходное состояние, как если бы приложение только запускалось. Если приложение остается в фоновом режиме за более короткое время, например, минуту или меньше, точки зрения сохраняются.
Кто-нибудь может понять, почему это может случиться? Буду признателен за любую помощь.
BuyerViewController:
- (void)viewWillAppear:(BOOL)animated{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate setTradeRole:@"buyer"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view sendSubviewToBack:mapView];
//checking if user is registered
PFUser *currentUser = [PFUser currentUser];
if(currentUser.email == nil || currentUser[@"FirstName"] == nil || currentUser[@"LastName"] ==nil || currentUser[@"PictureUrl"] == nil)
{
UIStoryboard *LoginStoryboard = [UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
UIViewController *LoginVC = [LoginStoryboard instantiateViewControllerWithIdentifier:@"FEXLogin"];
LoginVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:LoginVC animated:NO completion:nil];
return;
}
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
sellerArray = [[NSMutableArray alloc] init];
[mapView setDelegate:self];
[locationManager setDelegate:self];
if([[UIDevice currentDevice].systemVersion floatValue] >= 8.00){
[locationManager requestWhenInUseAuthorization]; //needed for IOS 8
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone; //5 meters distance change will trigger update location
[locationManager startUpdatingLocation];
//Initial mapView settings
[self.view addSubview:mapView];
[mapView setCenterCoordinate:self.mapView.userLocation.coordinate];
mapView.showsUserLocation = YES;
mapView.zoomEnabled =YES;
mapView.scrollEnabled = YES;
addressField.hidden = NO;
editBuyerAddressButton.hidden = NO;
[mapView setUserTrackingMode:MKUserTrackingModeFollow animated:NO];
CLLocationCoordinate2D center = self.mapView.centerCoordinate;
pinLocation = [[CLLocation alloc] initWithLatitude:center.latitude longitude:center.longitude];//necessary to assign before [getSellersLocation]
//make sure in home page everybody is buyer
if(currentUser)
{
[currentUser setObject:[NSNumber numberWithBool:NO] forKey:@"isSeller"];
[currentUser setObject:[NSNumber numberWithBool:NO] forKey:@"isSelling"];
[currentUser saveInBackground];
}
//adding the buyerPinImage
buyerPinImage =[[UIImageView alloc] initWithFrame:CGRectMake((self.mapView.center.x-21), (self.mapView.center.y -56), 42, 56)];
buyerPinImage.image = [UIImage imageNamed:@"buyer.png"];
[self.view addSubview:buyerPinImage];
__weak __typeof__(self) weakSelf = self;
handleGeocoding = ^(NSArray *placemarks, NSError *error)
{
if(error == nil && [placemarks count] > 0)
{
weakSelf.placemark = [placemarks lastObject];
weakSelf.addressField.hidden = weakSelf.navigationItem.rightBarButtonItem ? YES : NO;
weakSelf.addressField.text = [NSString stringWithFormat:@" %@ %@ %@ %@", weakSelf.placemark.thoroughfare, weakSelf.placemark.subThoroughfare, weakSelf.placemark.postalCode, weakSelf.placemark.locality];
NSString *undesired = @"(null)";
NSString *desired = @"";
weakSelf.addressField.text = [weakSelf.addressField.text stringByReplacingOccurrencesOfString:undesired
withString:desired];
weakSelf.editBuyerAddressButton.hidden = NO;
}
if([weakSelf.addressField.text isEqualToString:@" "])
weakSelf.addressField.text = @" Vent venligst";
};
CLLocation *plocation = [[CLLocation alloc] initWithLatitude:mapView.userLocation.coordinate.latitude longitude:mapView.userLocation.coordinate.longitude];
[geocoder reverseGeocodeLocation:plocation completionHandler: handleGeocoding];
[self.view addSubview:toCurrentLoc]; //enables button to current location
[self.view addSubview:callButton]; //enables showing small container view
[self.view addSubview:containerView]; //enables showing container view
[self.view addSubview:paymentView]; //enables showing payment view
navTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
navTitleLabel.backgroundColor = [UIColor clearColor];
navTitleLabel.font = [UIFont boldSystemFontOfSize:15.0];
navTitleLabel.textAlignment = NSTextAlignmentCenter;
navTitleLabel.textColor = [UIColor themeColor];
navTitleLabel.text = @"";
self.navigationItem.titleView = navTitleLabel;
[self.navigationItem setRightBarButtonItem:nil];
buyButton.hidden = NO;
containerView.hidden = YES;
callButton.hidden = YES;
ratingView.hidden = YES;
[hudContactSellers hide:YES];
[mapView removeAnnotation:buyersPin];
tradeState = NoTrade; //notrade
contactingSellers = NO;
[NSTimer scheduledTimerWithTimeInterval:6 target:locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES];
//Notification Settings
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenSeller:) name:@"listenSeller" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenTradeEnded:) name:@"listenTradeEnded" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listeBuyerResponded:) name:@"listenBuyerResponded" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenTradeCancelledBySeller:) name:@"listenTradeCancelledBySeller" object:nil];
// Configure Star Layout
[ratingView setStepInterval:1];
[ratingView setValue:5];
[ratingView setBaseColor:[UIColor grayColor]];
[ratingView setMarkFont:[UIFont systemFontOfSize:32.0f]];
// Make Sure Button Is Visible
[self.view bringSubviewToFront:buyButton];
[self.view bringSubviewToFront:addressField];
[self.view bringSubviewToFront:editBuyerAddressButton];
}
Покажите свое представление, загрузите и просмотрите, появились методы !!!!! –
переместить весь код из представления, загрузился ли он для просмотра, и посмотреть, существует ли проблема или нет. –
@ Mr.T Я пробовал это, но то же самое произошло. кстати, я не хочу, чтобы приложение переходило к настройкам viewdidload, которые на самом деле я хочу избежать. – ESG