将数据发布到json Web服务后,我需要提醒用户数据是否已成功保存。我对此没有任何问题,但在日志中获得“数据已成功保存”响应后,视图需要很长时间(大约40-50秒)才能显示警报视图。我可以在几秒钟内得到响应后立即帮助我获取警报视图吗?这就是我做的事情
NSURL *url = [NSURL URLWithString:@"some url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if(error || !data)
{
NSLog(@"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Data not saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(@"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Response is %@", jsonObject);
NSString *code = [jsonObject valueForKey:@"Code"];
NSLog(@"Code value = %@", code);
if([code intValue] == 0)
{
[activity stopAnimating];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data updated!" message:@"Entered data above has been saved in the database successfully." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
else
{
[activity stopAnimating];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data not saved" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
[alert show];
}
}
}];
}
答案 0 :(得分:5)
我认为你是从一个单独的线程调用警报视图代码。所有UI元素都需要从主线程处理。
在您的情况下,您应该更改为以下内容,
[activity performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
[alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
或者你可以用GCD做到这一点,
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Data not saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertMessage show];
});
希望有所帮助!
答案 1 :(得分:1)
您应该在主线程中的块内进行所有UI交互。只需使用以下代码
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data updated!" message:@"Entered data above has been saved in the database successfully." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
});