• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 将数据传递给另一个 View Controller

[复制链接]
菜鸟教程小白 发表于 2022-12-13 12:39:28 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有两个 View Controller (DatePickerViewControllerRouteHistoryViewController)。我在 DatePickerViewController 中也有服务器响应。如何将该响应传递给 RouteHitoryViewControllerRouteHistoryViewController 有一个 map View 。

这里是代码DatePicker.m:

#import "DatePickerViewController.h"
#import "MapAnnotation.h"

@interface DatePickerViewController ()


@end

@implementation DatePickerViewController
{
    //#define URL @"http://140e3087.ngrok.com"
#define URL3 @"http://784effb4.ngrok.com/bustracking/json/student/route_history"
    NSString *formatedDate;
    NSString *lat;
    NSString *longi;
    NSString *server_created_date;


}
@synthesize appDelagate,datePicker;

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"%@", appDelegate);

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat"yyyy-MM-dd HH:mm"];

    formatedDate = [dateFormatter stringFromDate:self.datePicker.date];


    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)sendPickerid)sender;
{
    [self sendDataToServer : @"GET"];

   // NSLog(@"%@", formatedDate);

    //self.selectedDate.text =formatedDate;
}

-(void) sendDataToServer : (NSString *) method{


    NSString *beaconiD = @"EC112729B51B";
    NSString *trackerID = @"e61078a67e4233ad";//appDelagate.tracker_id;
    NSString *date = formatedDate;


    NSMutableURLRequest *request = nil;
    NSString *getURL = [NSString stringWithFormat"%@?beacon_id=%@&tracker_id=%@&date=%@", URL3, beaconiD, trackerID, date];
    getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url =  [NSURL URLWithString: getURL];
    request = [NSMutableURLRequest requestWithURL:url];

    NSLog(@"link: %@", getURL);

    [request setHTTPMethod"GET"];
    [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField"Content-Type"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    NSLog(@"connection: %@", connection);

    if( connection )
    {
        mutData = [NSMutableData new];
    }
    else
    {
        NSLog (@"NO_CONNECTION");
        return;
    }
}

#pragma mark NSURLConnection delegates

-(void) connectionNSURLConnection *) connection didReceiveResponseNSURLResponse *)response
{
    [mutData setLength:0];
}

-(void) connectionNSURLConnection *)connection didReceiveDataNSData *)data
{
    [mutData appendData:data];
}

-(void) connectionNSURLConnection *)connection didFailWithErrorNSError *)error
{

    NSLog (@"NO_CONNECTION");

    return;
}

-(void)connectionDidFinishLoadingNSURLConnection *)connection
{

//        NSString *jsonresultString =[jsonresultDict objectForKey"result"];
//        NSLog(@"%@", jsonresultString);
//        //serverResponse.text = jsonresultString;

        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:mutData options:kNilOptions error:&error];
        NSArray *fetchedArr = [json objectForKey"result"];


        for (NSDictionary *user in fetchedArr)
        {


            lat = [user objectForKey"latitude"];
            longi = [user objectForKey"longitude"];
            server_created_date = [user objectForKey"server_created_date"];

            NSLog(@"Item date&time : %@", server_created_date);
            NSLog(@"Item longitude : %@", longi);
            NSLog(@"Item latitude : %@", lat);
        }



} 

这里是代码RouteHistory.m:

#import "RouteHistoryViewController.h"
#import "MapAnnotation.h"

@interface RouteHistoryViewController ()

@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@end

@implementation RouteHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.mapView.delegate = self;

    //[self.mapView removeAnnotations:self.mapView.annotations];

    MapAnnotation *mapPoint = [[MapAnnotation alloc] init];
    mapPoint.coordinate = CLLocationCoordinate2DMake([self.appDelagate.latitude doubleValue], [self.appDelagate.longitude doubleValue]);
    mapPoint.title = self.appDelagate.name;
    mapPoint.time = self.appDelagate.server_created_date;
    mapPoint.mapimage = self.appDelagate.image;

    // Add it to the map view
    [self.mapView addAnnotation:mapPoint];

    // Zoom to a region around the pin
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);

    [self.mapView setRegion:region];


    //testing
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selectorselector(receiveTestNotification
                                                 name:@"MapUpdate"
                                               object:nil];


    // Do any additional setup after loading the view.
}
#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapViewMKMapView *)mapView viewForAnnotationid<MKAnnotation>)annotation
{
    MKPinAnnotationView *view = nil;
    static NSString *reuseIdentifier = @"MapAnnotation";

    // Return a MKPinAnnotationView with a simple accessory button

    view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
    if(!view)
    {
        view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
        view.canShowCallout = YES;
        view.animatesDrop = YES;
    }

    return view;
}

datepicker 使用 prepareforsegue 路由历史记录

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if ([[segue identifier]isEqualToString:@"b"])
    {
        RouteHistoryViewController *rh = segue.destinationViewController;


        NSLog(@"%@", rh);

    }

}



Best Answer-推荐答案


在此行之后的第一个 View Controller 中的 connectionDidFinishLoading

    NSArray *fetchedArr = [json objectForKey:@"result"];

添加以下两行

 _responseFromServer = fetchedArr; 
[self performSegueWithIdentifier:@"segueToRouteHistory" sender:self];

然后在你的第一个 View Controller 中添加这个方法

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

 if ([[segue identifier] isEqualToString:@"segueToRouteHistory"])
 {


     RouteHistoryViewController *routeHistoryController = [segue segueToRouteHistory];

     [routeHistoryController setFetchedArray:_responseFromServer];

  }
}

在你的 First View Controller .h 文件中添加这个

@property NSArray *responseFromServer;

现在我们已经将从服务器接收到的响应数组分配给目标 View Controller 中的一个对象。

别忘了添加

@property NSArray *fetchedArray; 

在您的第二个 ViewController 的 .h 文件中

现在您可以在第二个 View Controller 中访问该数组。 PS:不要忘记将 Storyboard从第一个 View Controller 转移到第二个 View Controller ,并将 Segue Identifier 命名为“segueToRouteHistory”

关于ios - 将数据传递给另一个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303612/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap