从Obj-C(Xcode)中的URL获取数据(浮点数)

时间:2015-05-16 13:30:02

标签: php ios xcode

我对Xcode和iOS有点新意。我想从url请求获取数据,特别是浮点数据,并将其存储在数组中。例如,我有网址:

http://www.hazewatch.unsw.edu.au/get-data.php?latitudes=-33.91714104308085&longitudes=151.2331476539389&datetimes=2015-05-13%2003:27:52&pollutants=co

如果我在浏览器中输入该网址,则会显示文字' co = 0.1124'。如何将这些数据(0.1124)存入我的程序?这是我写的(下面),但这是不正确的。

NSString *stringPollution = [NSString stringWithFormat:@"http://www.hazewatch.unsw.edu.au/get-data.php?latitudes=-33.91714104308085&longitudes=151.2331476539389&datetimes=2015-05-13%2003:27:52&pollutants=co"];
NSURL *urlPollution = [NSURL URLWithString:stringPollution];
NSData *pollutionData = [NSData dataWithContentsOfURL:urlPollution];

这似乎是一项简单的任务,但我不知道该怎么做。任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

viewController.h

NSMutableData *responseData;
NSURLConnection *connection;

并添加<NSURLConnectionDataDelegate>

ViewDidLoad方法

NSString *urlString = @"http://www.hazewatch.unsw.edu.au/get-data.php?latitudes=-33.91714104308085&longitudes=151.2331476539389&datetimes=2015-05-13%2003:27:52&pollutants=co";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NO timeoutInterval:20.0f];


    responseData = [[NSMutableData alloc] init];
    connection = [NSURLConnection connectionWithRequest:request delegate:self];

ViewController.m

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Your Data :%@",newStr);
}

答案 1 :(得分:0)

简单的伙伴只需用以下代码替换您的代码

NSString *stringPollution = [NSString stringWithFormat:@"http://www.hazewatch.unsw.edu.au/get-data.php?latitudes=-33.91714104308085&longitudes=151.2331476539389&datetimes=%@&pollutants=co",@"2015-05-13%2003:27:52"];
NSURL *urlPollution = [NSURL URLWithString:stringPollution];
NSData *pollutionData = [NSData dataWithContentsOfURL:urlPollution];

NSString *myString = [[NSString alloc] initWithData:pollutionData
                                           encoding:NSUTF8StringEncoding];


NSLog(@"%@",myString);
  1. 使用特定格式将网址添加到字符串中。
  2. 在网址中传递字符串。
  3. 以NSData格式从网址获取数据。
  4. 将NSData转换为字符串格式。
  5. 使用 NSLog
  6. 检查控制台中的输出

    由于