我正在创建一个应用程序,它从服务器获取 JSON 文本并将其转换为机器人锦标赛的比赛时间表。我有自定义单元格,其中填充了我从网站收到的数据,它们显示每个匹配项的数据都很好。问题是,当我将匹配项放入 .plist 文件(“data.plist”)中时,一旦最初建立了互联网连接,用户不一定需要在应用程序被终止后重新连接到互联网查看当天的比赛时间表。在我不连接到 Internet 之前,我的代码可以完美运行。出于某种原因,一旦互联网连接失败,该应用程序永远不会进入创建单元格的功能。请帮忙!!这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
aRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://jrl.teamdriven.us/source/scripts/getElimMatchResultsJSON.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
aConnection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
if(aConnection){
receivedData = [NSMutableData data];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Connection!!" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
jrlDirectory = [paths objectAtIndex:0];
path = [jrlDirectory stringByAppendingPathComponent:@"data.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:@"data.plist"]) {
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"] toPath:path error:nil];
}
dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
// Prevents data from repeating itself
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData: data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Success! Received %d bits of data", [receivedData length]);
// Must allocate and initialize all mutable arrays before changing them
sweet16 = [[NSMutableArray alloc]init];
quarterfinals = [[NSMutableArray alloc]init];
semi = [[NSMutableArray alloc]init];
finals = [[NSMutableArray alloc]init];
dict = [[NSMutableDictionary alloc]init];
// The error is created and can be referred to if the code screws up (example in the "if(dict)" loop)
NSError *error;
dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&error];
matchNames = [[dict objectForKey:@"ElimMatchListResults"]allKeys];
matchNames = [matchNames sortedArrayUsingSelector:@selector(compare:)];
// Categorize the matches based on the first two letters of their match names
for (NSString *name in matchNames) {
if([[name substringToIndex:2]isEqual:@"16"]){
[sweet16 insertObject:[[dict objectForKey:@"ElimMatchListResults"] objectForKey:name] atIndex:sweet16.count];
}
else if([[name substringToIndex:2]isEqual:@"Q."]){
[quarterfinals insertObject:[[dict objectForKey:@"ElimMatchListResults"]objectForKey:name] atIndex:quarterfinals.count];
}
else if([[name substringToIndex:2]isEqual:@"S."]){
[semi insertObject:[[dict objectForKey:@"ElimMatchListResults"]objectForKey:name] atIndex:semi.count];
}
else if([[name substringToIndex:2]isEqual:@"F."]){
[finals insertObject:[[dict objectForKey:@"ElimMatchListResults"]objectForKey:name] atIndex:finals.count];
}
}
headers = [NSArray arrayWithObjects:@"Sweet 16", @"Quarterfinals", @"Semifinals", @"Finals", nil];
sections = [NSArray arrayWithObjects:sweet16, quarterfinals, semi, finals, nil];
// If the dictionary "dict" gets filled with data...
if (dict) {
[[self tableView]setDelegate:self];
[[self tableView]setDataSource:self];
// Now uses data storage so that the user only needs to initially connect to the internet and then they can keep the schedule afterwords
[dataDict setObject: [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithArray:sections], @"sections",
[NSArray arrayWithArray:headers], @"headers",
nil]
forKey:@"Matches"];
[dataDict writeToFile:path atomically:YES];
}
else{
NSLog(@"%@", error);
}
}
// Set the number of sections based on how many arrays the sections array has within it
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] count];
}
// Set the number of rows in each individual section based on the amount of objects in each array
// within the sections array
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:section] count];
}
// Set headers of sections from the "headers" array
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [[[dataDict objectForKey:@"Matches"] objectForKey:@"headers"] objectAtIndex:section];
}
// Create cells as the user scrolls
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"Entered Final Loop");
static NSString *cellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell){
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.matchNum.text = [[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"MatchID"];
cell.red1.text = [NSString stringWithFormat:@"%@",[[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Red 1"]];
cell.red2.text = [NSString stringWithFormat:@"%@",[[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Red 2"]];
cell.redScore.text = [NSString stringWithFormat:@"%@", [[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Red Score"]];
cell.blue1.text = [NSString stringWithFormat:@"%@",[[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Blue 1"]];
cell.blue2.text = [NSString stringWithFormat:@"%@",[[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Blue 2"]];
cell.bluescore.text = [NSString stringWithFormat:@"%@", [[[[[dataDict objectForKey:@"Matches"] objectForKey:@"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Blue Score"]];
return cell;
}
对于冗长的代码,我深表歉意,我只是想确保我了解了所有详细信息。请提出您需要的任何问题以进行澄清,我现在真的很困惑和慌乱,不知道为什么如果没有互联网连接,它永远不会进入创建单元格的功能。
最佳答案
几个 react :
您的 fileExistsAtPath 看起来不正确。当然你应该有完全合格的路径,例如:
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"] toPath:path error:nil];
}
我还可能建议您检查 copyItemAtPath 是否成功(返回值或使用 error 参数)。
我假设您知道 data.plist 永远不会在 viewDidLoad 完成之前成功刷新(因为连接是异步启动的,您会立即从 initWithRequest)。此代码只是加载最后的 data.plist 值,同时检索新数据 yield (尽管有先前的错误)。这是你的期望吗?
除我之前的观点外,您的 connectionDidFinishLoading 似乎没有发出对表的 reloadData 调用,所以您似乎总是看之前的数据。连接完成后,connectionDidFinishLoading 应该为 UITableView 调用 reloadData。
不相关的次要细节,但我可能会在 NSURLConnectionDataDelegate 方法 didReceiveResponse 中初始化 receivedData(并且仅当该响应也成功了)。它并不真正属于 viewDidLoad。
我可能还鼓励您检查 JSONObjectWithData 是否失败。一些网络故障表现为一个成功的 NSURLConnection 请求返回一个 HTML 页面 (!) 报告一个错误。该 HTML 页面将无法通过 JSONObjectWithData 处理。如果 JSONObjectWithData 返回 nil 或者如果 error 对象不是 nil,您可能想要中止您的解析例程。
关于ios - 缺少 Internet 连接会阻止创建单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17840528/
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下