【问题标题】:Getting wrong data with NSURLRequest when using multiple url's使用多个 url 时使用 NSURLRequest 获取错误数据
【发布时间】:2014-01-24 05:49:14
【问题描述】:

在我的项目中,我在同一个类中使用了 2 个 api。我想使用 NSURLRequest 获取数据,在第一个 api 中,我得到了地方的纬度经度,并将这些纬度经度放在第二个 url 上以获取这些地方之间的距离,但每个地方的距离都相同

这是我的代码。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    currentLocation = newLocation;

    if (currentLocation != nil){

        NSString *str=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=2000&types=%@&sensor=false&key=API Key",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude,strCatText];
        [self createTheConnection:str];
        //[self createTheConnection1:str1];

        arrAllData=[[NSMutableArray alloc]init];
        int i;
        for (i=0; i<=2; i++)
        {
            NSString *strname=[[[arr valueForKey:@"results"] objectAtIndex:i] valueForKey:@"name"];
            NSString *strvicinity=[[[arr valueForKey:@"results"] objectAtIndex:i] valueForKey:@"vicinity"];
            NSString *strRef=[[[arr valueForKey:@"results"]objectAtIndex:i]valueForKey:@"reference"];
            NSString *strLat=[[[[[arr valueForKey:@"results"] objectAtIndex:i] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lat"];
            NSString *strLng=[[[[[arr valueForKey:@"results"] objectAtIndex:i] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lng"];

            int j;
            for (j=0; j<=0; j++)
            {
               NSString *str1=[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%@,%@&sensor=false&mode=driving",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude,strLat,strLng];
                //NSLog(@"%@",str1);
                [self createTheConnection1:str1];

              //  if (![strLat isEqual:@"0"]) {
               //   strDistance=@"";
                  NSString *strDistance=[[[[[[arr2 valueForKey:@"routes"] objectAtIndex:0] valueForKey:@"legs"] objectAtIndex:0] valueForKey:@"distance"] valueForKey:@"text"];
               // NSLog(@"%@",strDistance);
                //}

                if(strname == nil){
                    strname = [NSString stringWithFormat:@"%@", [NSNull null]];
                }
                if(strvicinity == nil){
                    strvicinity = [NSString stringWithFormat:@"%@", [NSNull null]];
                }
                if(strRef == nil){
                    strRef = [NSString stringWithFormat:@"%@", [NSNull null]];
                }
                if(strDistance == nil){
                    strDistance = [NSString stringWithFormat:@"%@", [NSNull null]];
                }

                if (![strDistance isEqual:@"<null>"]) {
                    arrdata=[[NSMutableArray alloc]initWithObjects:strname,strvicinity,strRef,strDistance, nil];
                    strDistance=nil;

                    [arrAllData addObject:arrdata];
                }       

            }          
           [tblView reloadData];  
        } 
    }



-(void)createTheConnection:(NSString*)strUrl
{    
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

    connections=[[NSURLConnection alloc]initWithRequest:request delegate:self];

    if(connections)
    {
        webData=[NSMutableData data];

    }

}

-(void)createTheConnection1:(NSString*)strUrl1
{

    NSMutableURLRequest *request1=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[strUrl1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

    connections1=[[NSURLConnection alloc]initWithRequest:request1 delegate:self];

    if(connections1)
    {
        webData1=[NSMutableData data];

    }

}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

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

    self.navigationItem.leftBarButtonItem=nil;

}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (connection==connections) {
        [webData appendData:data];
    }
    if (connection==connections1) {
        [webData1 appendData:data];
    }


}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    if (connection==connections) {
        [webData setLength:0];
    }
    if (connection==connections1) {
        [webData1 setLength:0];
    }


}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{   

    NSError *err;   
    if (connection==connections) {
        arr=[NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&err];
    }
    if (connection==connections1) {
        arr2=[NSJSONSerialization JSONObjectWithData:webData1 options:NSJSONReadingMutableContainers error:&err];      
    }  
}


-(void)barBtnItem1{
    MapViewController *mvc =[self.storyboard instantiateViewControllerWithIdentifier:@"mapview"];
    [UIView beginAnimations:@"Start" context:nil];
    [UIView setAnimationDuration:0.80];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
    [self.navigationController pushViewController:mvc animated:YES];
    [UIView commitAnimations];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arrAllData.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    UILabel *lblName=(UILabel*)[cell viewWithTag:100];
    UILabel *lblAddress=(UILabel*)[cell viewWithTag:101];
    UILabel *lblDistance=(UILabel*)[cell viewWithTag:102];
    arrData11=[arrAllData objectAtIndex:indexPath.row];
    NSString *strName=[NSString stringWithFormat:@"%@",arrData11[0]];
    NSString *strAddress=[NSString stringWithFormat:@"%@",arrData11[1]];
    NSString *strDistance1=[NSString stringWithFormat:@"%@",arrData11[3]];
    if ([strName isEqual:@"<null>"]) {
//        lblName.text=@"Loading...";
//        lblAddress.text=@"Loading...";
    }
    else{
        lblName.text=strName;
        lblAddress.text=strAddress;
        lblDistance.text=strDistance1;
    }
        return cell;
}

【问题讨论】:

  • 所有代码都可用@suhit

标签: ios iphone objective-c nsurlconnection grand-central-dispatch


【解决方案1】:

您正在创建两个背靠背连接,当他们收到数据时,他们正在调用代表,但在您的应用程序中,您没有等待从第一个请求中获取数据,然后发出第二个请求。我很确定你得到的距离是第二个经纬度的距离。

对这些数据提出单一请求,然后查看您获得的距离。并尝试一一提出要求。即提出第一个请求..获取数据..然后提出第二个请求。因为他们使用相同的委托来初始化数据。

编辑 我在手机上,所以我无法帮你写代码。我试试看。。

Method A (take parameter that you need to make a url request) {
    //Make request with pair of lat and long and necessary datas
}

(void)connectionDidFinishLoading:(NSURLConnection *)connection{   
    ........
    //After getting the data

    Call method A with next pair of lat long 
    You can determine next pair by maintaining a global variable.
}

让我知道这有帮助...:)

【讨论】:

  • 我该如何处理这个问题,我对 GCD 很陌生..告诉我 PLZ
  • 是的,我已经解决了我的问题,但不是以这种方式....我使用 CLLocation 来获取距离。 @Rashad
猜你喜欢
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 2023-04-11
相关资源
最近更新 更多