mark
mark

Reputation: 199

Getting delay to see next view controller ,see detail in post?

I have one login screen after that it will move to next view controller which have i have used some networks like http,json to get data from server. when i enter login username/password then if i click login button its getting delay to 8 seconds after that only it moving to next view controller.Still that my login screen alone showing for 8 seconds and then only it move to next view controller.

Here my login controller.m:

@implementation mainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _username.delegate = self;
    _password.delegate = self;

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults boolForKey:@"reg"]) {
        NSLog(@"no user reg");
        _logBtn.hidden = NO;
    }




}



- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];

    _username.text = nil;
    _password.text = nil;


}


 - (IBAction)LoginUser:(id)sender {



    if ([_username.text isEqualToString:@"sat"] && [_password.text isEqualToString:@"123"]) {
        NSLog(@"Login success");



        [self performSegueWithIdentifier:@"nextscreen" sender:self];


       }
    else {

        NSLog(@"login was unsucess");
        // Alert message


        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"wrong"

                                                                                 message:@"Message"

                                                                          preferredStyle:UIAlertControllerStyleAlert];



        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"

                                                           style:UIAlertActionStyleDefault

                                                         handler:nil];

        [alertController addAction:actionOk];

        [self presentViewController:alertController animated:YES completion:nil];


    }

}

Here my nextcontroller.m

 - (void)viewDidLoad {
        [super viewDidLoad];
//for search label data
        self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
         titleArray = [NSMutableArray array];


// here only i am getting data from server
        [self getdata];


        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
       [self.collectionView reloadData];


     }

Help me out. If my question din't understand.I can tell more about my post. And in my nextcontroller.m [self getdata] is i am getting data from server url.Thanks

My get data:

-(void)getdata {

    NSString *userName = @“users”;
    NSString *password = @“images”;
    NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [plainData base64EncodedStringWithOptions:0];
    base64String=[self sha256HashFor: base64String];

    NSString *urlString = @"https://porterblog/image/file”;

    NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"GET"];



    NSString *authStr = [NSString stringWithFormat:@"%@:%@", userName, base64String];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];



    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];

      [request setValue:authValue forHTTPHeaderField:@"Authorization"];





   NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];


    NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];


    NSError * error;

    self->arrayPDFName = [[NSMutableArray alloc]init];
    NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];



    NSDictionary *dictOriginal = jsonResults[@“birds”];
    [titleArray addObject:[NSString stringWithFormat:@" birds(%@)”, dictOriginal[@"count"]]];


    NSDictionary *dictOriginal2 = jsonResults[@"owl”];
    [titleArray addObject:[NSString stringWithFormat:@" Owl(%@)”, dictOriginal2[@"count"]]];



    NSDictionary *dictOriginal3 = jsonResults[@"pensq”];
    [titleArray addObject:[NSString stringWithFormat:@" Pensq(%@)”, dictOriginal3[@"count"]]];


    NSDictionary *dictOriginal4 = jsonResults[@“lion”];
    [titleArray addObject:[NSString stringWithFormat:@" lion(%@)”, dictOriginal4[@"count"]]];




    NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];


     NSLog(@"str: %@", titleArray);


    for (NSDictionary *dict in arrayFiles) {
        NSMutableArray *arr = [NSMutableArray array];

        NSArray *a = dict[@"files"];
        for(int i=0; i < a.count; i ++) {


            NSString *strName = [NSString stringWithFormat:@"%@",[[dict[@"files"] objectAtIndex:i] valueForKey:@"name"]];

            [arr addObject:strName];
        }
        [arrayPDFName addObject:arr];
    }


    NSString *errorDesc;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory1 = [paths objectAtIndex:0];
    NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:@"SampleData.plist"];

    NSString *error1;

    returnData  = [ NSPropertyListSerialization dataWithPropertyList:jsonResults format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];


    if(returnData ) {
        if ([returnData  writeToFile:plistPath atomically:YES]) {
            NSLog(@"Data successfully saved.");
        }else {
            NSLog(@"Did not managed to save NSData.");
        }
    }
    else {
        NSLog(@"%@",errorDesc);
    }


    NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];



}

EDITED:

`- (void)viewDidLoad {

    [super viewDidLoad];

  dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){



        self.dataSourceForSearchResult = [NSArray new];

        titleArray = [NSMutableArray array];



        //Background Tasks

        [self getdata];

        dispatch_async(dispatch_get_main_queue(), ^(void){

            //Run UI Updates

 self.collectionView.dataSource = self;

                self.collectionView.delegate = self;

               [self.collectionView reloadData];

         self.navigationItem.hidesBackButton = YES;

  });

    });

 }`

Upvotes: 1

Views: 80

Answers (1)

Dekel Maman
Dekel Maman

Reputation: 2097

You're getting your data using main thread you need do to that in background then invoke the code you need (as i see is reload collectionView) I assume that because you didn't show the getdata method code If that the case you can use this code:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Tasks
    [self getdata];
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
        [self.collectionView reloadData];
    });
});

It's mean that your VC will show immediately but the collectionView fill after you finish load the data, you can put some old data while loading like Facebook app (you see latest retrieved posts until finish loading].

Edit: In your code you replace viewdidload method in nextController with next code:

- (void)viewDidLoad {
  [super viewDidLoad];
  //for search label data
  self.dataSourceForSearchResult = [NSArray new];
  //collection of array to store value
  titleArray = [NSMutableArray array];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Tasks
    [self getdata];
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
        [self.collectionView reloadData];
    });
    });

self.collectionView.dataSource = self;
self.collectionView.delegate = self;

}

Upvotes: 1

Related Questions