關於互聯網上的每一個教程和示例,我都會看到如何從某個URL獲取JSON並在Tableview中顯示它。這不是我的問題我知道如何用AFNetworking框架或本地API來做到這一點。如何在UIView標籤中顯示JSON數據
我的問題是,我已經下載了JSON後,我想在我的UIView標籤中顯示它。當我試圖找到解決NSURLSession無法在iOS 8中緩存的方法時,我實際上成功地做到了這一點。但是我沒有意識到它是同步的。
Factory.m
+ (Factory *)responseJson
{
static Factory *shared = nil;
shared = [[Factory alloc] init];
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:@"http://urltojson.com/file.json"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:10.0];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(@"error");
} else {
//-- JSON Parsing
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
//NSLog(@"Result = %@",result);
shared.responseJson = result;
}
return shared;
}
我的問題是有可能使用例如AFNetwoking做同樣的事情?我失去了一些方法,我需要在類似的情況下調用的TableView
的
[self.tableView reloadData];
我想是因爲我需要檢查可達性,它似乎已經實現了它使用的框架。
編輯爲要求出示更多的代碼
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self factoryLoad];
[self setupView];
}
- (void)factoryLoad
{
Factory *shared = [Factory responseJson];
self.titles = [shared.responseJson valueForKeyPath:@"data.title"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
});
}
- (void)setupView
{
self.issueTitleLabel.text = [self.titles objectAtIndex:0];
}
所以,你在哪裏試圖把數據放到標籤這種方法嗎? – 2014-10-29 18:20:15
在viewDidLoad中。使用異步提取方法,我嘗試將提取方法放在viewWillAppear中,並設置viewDidLoad中的所有標籤,但這並不奏效。 – Pahnev 2014-10-29 18:25:07
你能編輯你的問題並顯示用於設置標籤文本的代碼嗎?如果您正在異步提取數據並將標籤文本設置爲完成處理程序之外,則可能會嘗試將文本設置爲一個實際不存在的值,因爲數據尚未提取。 – 2014-10-29 18:33:40