Search code examples
iosjsonswiftnsurlsessionnsjsonserialization

Class array object value always return nil after json serialization


I have created one function called "GetDataFromURL" which is main task to get data form URL and store into local Class Array object. using URlSession.shared.dataTask funcation i receive data into DATA Format and After that by use of jsonserialization.jsonObject method i get into json format. response is in dictionary format so store into temporary class object, at the end it will append to global class array object. this function is call while Page is called "View Load" method. Within the function it will display all data but every time i got nil array object while i display outside the block.

public class Modelclass : NSObject {

var id :Int!
var albumId : Int!
var title : String!
var url : String!
var thumbnailUrl : string! 

}

this is Class file and below is viewcontroller file :

var temp:[ModelClass]? 

override func viewDidLoad() {

super.viewDidLoad()
self.temp = [ModelClass]()
dispatchQueue.main.async{
    self.GetDataFromURL()
}

print(self.temp,"Tesing print")
}



  func GetDatafromURL() {

  if let url = URL(string : 
  "https://jsonplaceholder.typicode.com/photos"){
   URLSession.shared.dataTask(with: url){(data,response,error) in
    if error != nil {
        print(error)
        return
    }
    do{
        let jsonresponse = try jsonserialization.jsonObject(with:data! , 
        options: .mutablecontainers)
        for dictionary in jsonresponse as! [[String:AnyObject]]
        {
            var test = ModelClass()
            test.title = dictionary["title"] as? String
            test.albumId = dictionary["albumId"] as? Int
            test.id = dictionary["id"] as? Int
            test.thumbnailUrl = dictionary["thumbnailUrl"] as? String
            test.url = dictionary["url"] as? String
            self.temp?.append(test)
        }

    }
    catch let jsonerror{
        print(jsonerror)
    }
 }.resume()
}
}

it's show me " optional([]) Tesing print " as Output.and while print that temp object inside the do Block it will display all data.


Solution

  • here is Version For objetive c,

       @property (strong,nonatomic) NSMutableArray<UserModel *> *jsonarray ;
       @end
    
       @implementation ViewController
    
       dispatch_group_t serviceGroup;
       NSMutableDictionary *result ;
    
    
      - (void)viewDidLoad {
       [super viewDidLoad];
       // Do any additional setup after loading the view, typically from a nib.
    
        result = [[NSMutableDictionary alloc]init];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    
         UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
        [self.tableView registerNib:nib forCellReuseIdentifier:@"TableViewCell"];
        serviceGroup = dispatch_group_create();
    
    
        _jsonarray = [[NSMutableArray alloc]init];
    

    // \ [userdata GetDatafromUrl:@"https://jsonplaceholder.typicode.com/users"];

        [self GEtDataFromurl:@"https://jsonplaceholder.typicode.com/users"];
        }
    
    
    
     -(void)GEtDataFromurl:(NSString *) urlstr{
    
     dispatch_group_enter(serviceGroup);
    [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:urlstr] completionHandler:^(NSData *_Nullable data,NSURLResponse *_Nullable response, NSError *_error){
        NSError *err;
        NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
        if(err){
            NSLog(@"Falied to serialization.. ");
            return;
        }
    
        for (NSDictionary *UserDir in json){
            NSString *Id = UserDir[@"id"] ;
            NSString *name = UserDir[@"name"] ;
            NSString *username = UserDir[@"username"];
            NSString *email = UserDir[@"email"];
            NSString *phone = UserDir[@"phone"];
            NSString *website = UserDir[@"website"];
    
            struct company *company = CFBridgingRetain(UserDir[@"company"]);
            struct address *address = CFBridgingRetain(UserDir[@"address"]);
    
            UserModel *model = UserModel.new;
            model.Id =  [Id intValue];
            model.name = name;
            model.address = address;
            model.username = username;
            model.email  = email;
            model.phone = phone;
            model.website = website;
            model.company = company;
            NSLog(@"%@", model.name);
            [_jsonarray addObject:model];
    
        }
                dispatch_group_leave(serviceGroup);
    }]resume];
    
    dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
    
    
        NSLog(@" outside user class :  %@", _jsonarray);
    
        [self.tableView reloadData];
    });
    
    }
    

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; }

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
    if(cell == nil){
        NSArray *obj = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];
        cell = [obj objectAtIndex:0];
    }
    UserModel *model = _jsonarray[indexPath.row];
    cell.displaylabel.text = model.username;
    
    return  cell;
    

    }

    - (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:                (NSInteger)section {
     return _jsonarray.count;
    

    }

    @end