iOS Basic Request to webservice - ios

Can anyone point me in the right direction of a good tutorial or possibly answer this question.
I have some JSON to be returned on my web server
{
first_name: "Joe";
last_name: "Smith";
department: "Human Resources";
}
How do I make a http request to get this information at the click of a button and display as text on the iphone.?
Complete newbie so please 'dumb' down.

create a jsonviewcontroller class
#import <UIKit/UIKit.h>
#interface JSONViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
{
NSString *label;
}
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
- (IBAction)getTop10AlbumAction:(id)sender;
#end
then in implementation class:-
#import "JSONViewController.h"
#interface JSONViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSString *category;
}
#end
#implementation JSONViewController
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Failed with Error");
}
this is the place where actual parsing happens, we fetch the title of albums from respective dictionary and arrays. to understand this first go to this link http://jsonviewer.stack.hu/#http://itunes.apple.com/us/rss/topalbums/limit=10/json this is the json viewer which shows the structure of the content that we are going to access. dont panic! its really easy if u try parsing some json urls
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry=[feed objectForKey:#"entry"];
for (NSDictionary *dict in arrayOfEntry) {
NSDictionary *title=[dict objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self myTableView]reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//clear background color
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
//set cell text
cell.textLabel.text=[array objectAtIndex:indexPath.row];
//set cell accessory type
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
here we specify the itunes url that we are going to parse and make connection request
- (IBAction)getTop10AlbumAction:(id)sender {
NSURL *url=[NSURL URLWithString:#"http://itunes.apple.com/us/rss/topalbums/limit=10/json"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
[[self myTableView]reloadData];
}
#end
i hope i have made it clear enough!

I suggest you two different tutorials:
Creating a simple interface. Here is a sample from Apple that have a button and a text displayed: iOS Button - Label sample
Insert into controller code (i.e. changeGreeting:) the code that calls the webservice: iOS JSON Webservice tutorial

Related

Pass Json Value to UICollection View

i want to display my images in grid view. i have used UICollection view controller,data which is i'm passing in JSON format.i cant able to display images using JSON format. Can anyone pls find my mistake? Here is my code
#interface ReceipeCollectionViewController()
{
NSMutableData *webdata;
NSURLConnection *connection;
NSMutableArray *contentarray;
NSMutableArray *array;
}
#end
#implementation ReceipeCollectionViewController
(void)viewDidLoad
{
[super viewDidLoad];
[array removeAllObjects];
[[self collectionView]setDelegate:self];
[[self collectionView]setDataSource:self];
array = [[NSMutableArray alloc] init];
}
(void)viewDidAppear:(BOOL)animated
{
NSString *serverurl=#"http://wesotech.com/web/myrecipe/web_services/recipe_listing.php?";
NSURL *url=[NSURL URLWithString:serverurl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webdata=[[NSMutableData alloc]init];
}
else
{
NSLog(#"Connection failure");
}
}
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webdata appendData:data];
}
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Fail with error");
}
(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSArray *results=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:&error];
[array removeAllObjects];
[array addObjectsFromArray:results];
[[self collectionView]reloadData];
}
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webdata setLength:0];
}
(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [array count];
}
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.mySpinner stopAnimating];
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell.contentView viewWithTag:100];
recipeImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:#"image"]]]];
UITextField *recipeTitleView =(UITextField *)[cell.contentView viewWithTag:101];
recipeTitleView.text=[[array objectAtIndex:indexPath.row]valueForKey:#"recname"];
return cell;
}
#end
My JSON Format is,
[
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704658059030.jpg","recname":"Italian Chicken","recid":"1"},
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704653421637.jpg","recname":"Fast Food Friday","recid":"2"},
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704648912893.jpg","recname":"Honey Clazed Lamb Chops","recid":"3"}
]
Instead of escaping your URL with \, use percentage encoding in your JSON and decode it back to unescaped string using the below code
NSString *imageUrl = #"http%3A%2F%2Fwesotech.com%2Fweb%2Fmyrecipe%2Frecipeimages%2F2016080614704658059030.jpg";
NSString *url = [imageUrl stringByRemovingPercentEncoding];
Another important point: Since you are loading an image with http://, you should set Allow Arbitrary Loads to YES under App Transport Security Settings in your info.plist file.
Also, make a note that it is not advisable to set allow arbitrary loads as it would result in security issues. It would be better if you
could have all your network calls to use https://
Make a class of tableViewCell and assign that class name to cell of collectionView in utility area. Make the outlet of imageView in tableViewCell Class and access it in cellForItemAtIndexPath delegate method.
Then assign the image with this code :
[cell. recipeImageView sd_setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:#"image"]]];
This will surely help you.

Segue performing in story

I have three ViewControllers. In first I open thirdViewController and in thirdViewController I open secondViewController. I use segue to perform seondViewController, but id doesn't work.
#import "thirdViewController.h"
#import "ViewController.h"
#import "DetailViewController.h"
#import "secondViewController.h"
#interface thirdViewController (){
NSDictionary *currencies;
NSMutableArray *arrayCurrenciesKeys;
NSMutableData *webData;
NSURLConnection *connection ;
NSMutableArray *array;
NSMutableArray *temp;
}
#end
#implementation thirdViewController
#synthesize tableView,cityname;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"Типи валют";
[[self tableView]setDelegate:self];
[[self tableView]setDataSource:self];
array=[[NSMutableArray alloc]init];
NSURL *url =[NSURL URLWithString:#"http:resources.finance.ua/ua/public/currency-cash.json"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
connection= [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData=[[NSMutableData alloc] init];
}
tableView.backgroundColor=[UIColor clearColor];
tableView.alpha=0.9;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [array count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier =#"Cell"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return cell;
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error");
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed =[allDataDictionary objectForKey:#"organizations";
for(NSDictionary *diction1 in feed){
NSString *label1 = [diction1 objectForKey:#"cityId"];
[temp addObject:label1];
NSString *label2 =[[allDataDictionary objectForKey: #"cities" ] objectForKey:[NSString stringWithFormat:#"%#",label1]];
if(![array containsObject:label2]){
[array addObject:label2];}
else{
;
}
[[self tableView]reloadData];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"Banks" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"Banks"]) {
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Also i add segue identificator in the storyboard. I also try to present it with navigation controller,but it doesn't work too.
I have three ViewControllers. In first I open thirdViewController and in thirdViewController I open secondViewController. I use segue to perform seondViewController, but id doesn't work.
I assume that your "first" is ViewController.h
1- Are you sure that the identifier of the segue from thirdViewController to secondViewController is #"Banks"?
You can be misleading it with the identifier of the segue from ViewController to thirdViewController.
2- Double check that you have the exact same string in Interface Builder and in code.
It can be #"Bankss" in Interface Builder and can be #"Banks" in code.

tableView unable to display data parsed from the web in json format

I created an api using kimono and here is my code.
#import "PlayerRankingsTableViewController.h"
#import "RankingsTableViewCell.h"
#define kBgQueue dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kPlayerRankingsURL [NSURL URLWithString:#"https://www.kimonolabs.com/api/bg6tcuuq?apikey=xgp4nU6xA9UcBWSe0MIHcBVbAWz5v4wR"]
#interface PlayerRankingsTableViewController () {
}
#property (nonatomic, strong) NSArray *playerRankings;
#end
#implementation PlayerRankingsTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:
kPlayerRankingsURL];
[self performSelectorOnMainThread: #selector(initializePlayerRankingsArray:)
withObject:data waitUntilDone:YES];
});
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be rexrcreated.
}
- (NSArray *)initializePlayerRankingsArray:(NSData *)responseData {
NSError* error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray *myPlayerRankings = [[json objectForKey:#"results"]objectForKey:#"collection1"];
self.playerRankings = myPlayerRankings;
NSLog(#"%#", self.playerRankings);
return self.playerRankings;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.playerRankings count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RankingsTableViewCell *cell = (RankingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = (RankingsTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
NSDictionary *rankings = [self.playerRankings objectAtIndex: indexPath.row];
NSString *rank = [rankings objectForKey:#"rank"];
NSString *name = [rankings objectForKey:#"name"];
NSString *points = [rankings objectForKey:#"points"];
[cell.playerRank setText:rank];
cell.playerName.text = name;
cell.playerPoints.text = points;
return cell;
}
#end
I think there is nothing wrong with data parsing process, because the console displays my data parsed from the web correctly.
However, when I ran the app, I saw nothing but a empty table.
Again, I think this might be something simple and new to programming.
Thank you in advance, and sorry for being such a burden.
In initializePlayerRankingsArray: you shouldn't be returning the array because nothing it there to receive it. You have already set self.playerRankings, so that is enough.
What is missing from this method is [self.tableView reloadData]; (which should be the last line after self.playerRankings is set).

How to show json data in table view in xcode

i am new to ios and am currently working in json. I am just using itunes top 10 albums which to be displayed in table view i received data i formatted and displayed in table view but i can able to display only album name but i want to display all details of particular album which is to be displayed in same cell.
Here is my full code
- (void)viewDidLoad
{
[super viewDidLoad];
albumtop=[[NSMutableArray alloc]init];
[[self itunestTable]setDataSource:self];
[[self itunestTable]setDelegate:self];
NSURL *url=[NSURL URLWithString:#"https://itunes.apple.com/in/rss/topalbums/limit=10/json"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
albumdata =[[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[albumdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[albumdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"error in connection");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *alldata =[NSJSONSerialization JSONObjectWithData:albumdata options:0 error:nil];
NSDictionary *album =[alldata objectForKey:#"feed"];
NSArray *total =[album objectForKey:#"entry"];
for(NSDictionary *top in total)
{
NSDictionary *albumname =[top objectForKey:#"im:artist" ];
title =[albumname objectForKey:#"label"];
[albumtop addObject:title];
}
[[self itunestTable]reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [albumtop count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if(!cell)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier];
}
cell.textLabel.text=[albumtop objectAtIndex:indexPath.row];
return cell;
}
Program working well
My output will be like this
---------------------------------
Jones
---------------------------------------
carry Kim
---------------------------------------
i can able to fetch single value only how can i display all the details of the album like this
----------------------------------
Jones
no.tracks 10
price 180
---------------------------------------
carry Kim
no.tracks 10
price 180
---------------------------------------
how i can achieve this help me.. thanks in advance
You need to add Thee label in your UITableViewCell.
And fetch each Value as you needed. It is simple fetch as you fetch value of name and put it to relevant UILabel.
You also need to expand size of your cell of UITableView by following method.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
return 80;// write as you need.
}
you have to use costum UITableviewCells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BDCustomCell"];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"BDCustomCell" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
}
return cell;
}

Refresh table view?

I think I have a pretty easy task, but somehow it doesn't want to work. I am a total beginner in objective-c, so I guess it's just a small mistake. I still don't really know what I do, currently it's more like copy&paste programming. Like I don't really know if I need the IBOutlet in the interface or as a property or as both.
What I have:
A ViewController with a Button, a Label and a Table View. The button connects to a sharepoints server and reads a list and adds the value to an array. This part works.
Delegate and DataSource outlet is connected to the View Controller.
What I want:
The array should be the datasource of the Table View, so I just want it to refresh after I've read the new data in the array. The test data I add in the viewDidLoad function to the array, shows up. So I guess I somehow connected the array to the table view.
I'll give you the full code:
ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
IBOutlet UILabel *output;
IBOutlet UITableView *tableView;
NSMutableData *webData;
NSString *finaldata;
NSString *convertToStringData;
NSMutableString *nodeContent;
}
#property (nonatomic, retain) UILabel *output;
#property (nonatomic, weak) IBOutlet UITableView *tableView;
-(IBAction)invokeService:(UIButton *) sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *foundUrlaub;
}
#end
#implementation ViewController
#synthesize output;
- (void)viewDidLoad
{
[super viewDidLoad];
// SOME TEST DATA... THIS SHOWS UP IN MY TABLE VIEW
foundUrlaub = [[NSMutableArray alloc]init];
[foundUrlaub addObject:#"first cell"];
[foundUrlaub addObject:#"second cell"];
[foundUrlaub addObject:#"third cell"];
}
-(IBAction)invokeService:(UIButton *) sender
{
// connection to sharepoint
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"didReceiveData");
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with the Connection");
NSLog(error.description);
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
NSLog(#"canAuthenticateAgainstProtectionSpace");
return YES;
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(#"didReceiveAuthenticationChallenge");
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"XXXXXX" password:#"XXXXXX" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
convertToStringData = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(?<=ows_Title=')(.*)(?=' ows_MetaInfo)" options:0 error:NULL];
NSArray *matches = [regex matchesInString:convertToStringData options:0 range:NSMakeRange(0, [convertToStringData length])];
// HERE I LOAD SOME DATA IN THE ARRAY
[foundUrlaub removeAllObjects];
for (NSTextCheckingResult *match in matches)
{
NSRange matchRange = [match rangeAtIndex:1];
NSString *matchString = [convertToStringData substringWithRange:matchRange];
NSLog(#"Match: %#", matchString);
[foundUrlaub addObject:matchString]; // <- ADDS 3 STRINGS TO ARRAY
}
// THIS DOES NOT WORK!
[tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [foundUrlaub count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [foundUrlaub objectAtIndex:indexPath.row];
return cell;
}
#end
try using [_tableView reloadData]; You didn't #synthesize your tableView in your .m so you have to use the autosynthesized identifier
Your code looks fine ,
make sure
IBOutlet for tableView is connected properly
Datasource and delegates from nib is connected to the files owner
A must watch and a must read for you
You have to connect the Outlet in the Interfacebuilder to your UITableview tableView.
You are trying to reload table from separate thread. so UIView can be changed only from main thread so do something like this:
[tableView performSelectorOnMainThread:#selector(reloadData)
withObject:nil
waitUntilDone:YES];

Resources