在此应用程序中,当用户按下按钮时,将向服务器发送 url 请求,并且应用程序将接收一些相应的数据。
我的问题是我想完全从服务器接收数据,当连接完成接收数据时,更改视图并将接收到的数据传递给另一个视图。
数据转换后,我收到错误并且应用程序崩溃。
我尝试了这种方法,但不知道我该怎么做。
问题已解决,代码已编辑
#import "ViewController.h"
@interface ViewController ()
//@property (nonatomic, strong) NSMutableData *responseData;
@end
@implementation ViewController
@synthesize responseData;
@synthesize myTableView;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"viewdidload");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Response received From the server.");
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"appending data to the response object.");
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError");
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Loading data succeeded! Received %d bytes of data",
[self.responseData length]);
//call the converter to convert the received
//Data to Json Packet and save to variable
[self convertDataToJson];
[self changePage];
}
-(void)changePage {
resultsTableViewController *myTableView = [[resultsTableViewController alloc]init];
myTableView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
myTableView=[myTableView init];
[self presentViewController:myTableView animated:YES completion:NULL];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
resultsTableViewController *mytable = [segue destinationViewController];
NSMutableArray * response = self.responseArray;
mytable.responseArray = response;
}
- (IBAction)get:(id)sender {
//making an instance of data query object and passing the word and dictionary selection to it.
if ( ![[searchField text]isEqualToString:@""] )
{
word = @”test”
[self makeRequestForWord:word withDictionaryName:@""];
// NSData *query = [word dataUsingEncoding:NSUTF8StringEncoding];
}
}
-(void)makeRequestForWord:(NSString*)word withDictionaryName:(NSString*)dicSelect;
{
//creating URL Request Object using given URL object.
//It requests data using nsConnection
}
- (void)convertDataToJson
{
// some conversion and save into responseDATA
}
- (void)viewDidUnload {
[super viewDidUnload];
}
@end
然后在与 segue 相关的功能中,我会将对象发送到下一个视图。