格式化NSURL

时间:2012-05-08 08:54:03

标签: objective-c nsurl

在我的应用中,我需要通过NSURL向Google方向服务提出json请求。

当URL是静态的时,我能够获得JSON响应。

NSURL *googleMapsURL=[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/directions/json?origin=SanFrancisco,CA&destination=Dallas,TX&waypoints=Los+Angeles,CA%7CHouston,TX&mode=driving&sensor=false"];


NSData *data=[NSData dataWithContentsOfURL:googleMapsURL];

但是,当我动态指定源站和目标站时,它无法正常工作。

NSString *urlString=[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&waypoints=Los+Angeles,CA%7CHouston,TX&mode=driving&sensor=false",sourceStation, destinationStation];

NSURL *googleMapsURL=[NSURL URLWithString:urlString];

NSData *data=[NSData dataWithContentsOfURL:googleMapsURL];

它会产生以下错误。

2012-05-08 03:30:15.960 SupplyTrackerApp2[3079:16403] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(0x19a7052 0x2448d0a 0x194fa78 0x194f9e9 0xecdfbd 0x2aae6 0x2a900 0x56ffbf 0x57021b 0x5704c3 0x580b71 0x5813df 0x581986 0x5815a4 0x34650 0x19a8ec9 0x4ab5c2 0x4ab55a 0x550b76 0x55103f 0x5502fe 0x4d0a30 0x4d0c56 0x4b7384 0x4aaaa9 0x1bbefa9 0x197b1c5 0x18e0022 0x18de90a 0x18dddb4 0x18ddccb 0x1bbd879 0x1bbd93e 0x4a8a9b 0x25cd 0x2535 0x1)
terminate called throwing an exception

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

对我看来,sourceStationdestinationStation似乎是nil。对于调试,您可以尝试在NSString *urlString定义之前的行中明确设置它们。

NSString *sourceStation = @"SanFrancisco,CA";
NSString *destinationStation = @"Dallas,TX";

如果这样可行,那么填写相应的NSString s ...

就会出现问题