【问题标题】:REST API call not getting Data when apps is debugging on device应用程序在设备上调试时 REST API 调用未获取数据
【发布时间】:2013-11-18 13:07:15
【问题描述】:

我正在通过以下方式在我的应用程序中调用 Rest API

-(NSArray*)parse_Data_From_URL:(NSString*)URL
{

    NSURL *myURL = [[NSURL alloc]initWithString:URL];

    // we'll receive raw data so we'll create an NSData Object with it
    NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];

    // now we'll parse our data using NSJSONSerialization
    id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];


    // typecast an array and list its contents

    NSArray *jsonArray = [NSArray new];
    jsonArray = (NSArray *)myJSON;

  //  NSLog(@"json floor plan imageTite --- %@",jsonArray);

    return jsonArray;

}

当我在 iPad 模拟器上运行我的应用程序时,我的代码运行良好,但是当我在 设备 上运行应用程序时,它 API 响应 得到空值并且应用程序正在运行终止。

【问题讨论】:

  • 1) NSArray *jsonArray = [NSArray new]; 是不必要的,因为您在它之后立即将 myJSON 分配给它。 2) 将myJSON 类型转换为NSArray 不会自动将对象转换为数组(例如,您可能会得到一个字典)。 3)只需在反序列化后设置一个断点并检查对象和任何错误。
  • 您确认您的设备有互联网连接吗?
  • Y 我的设备有互联网连接。

标签: ios objective-c ipad xcode5


【解决方案1】:

您不应忽视可能存在错误的事实:

-(NSArray*)parse_Data_From_URL:(NSString*)URL
{

    NSURL *myURL = [[NSURL alloc]initWithString:URL];

    // we'll receive raw data so we'll create an NSData Object with it
    NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];

    // now we'll parse our data using NSJSONSerialization
    NSError *err = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&err];

    if (err) {
        // do something about error
        NSLog("Error retrieving data: %@", err);
    }

    // this will be nil if there is an error.  May want to consider adding NSError ** to parse_Data_From_URL parameters
    return jsonArray;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2013-10-31
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多