【发布时间】:2026-01-26 16:30:01
【问题描述】:
大家好,我正在尝试使用 Yahoo 的 PlaceFinder 为我正在制作的应用程序进行反向地理编码。问题是我需要使用 NSURLConnection 来调用我的数据库。所以我决定做一个自定义类,用用户的经纬度进行初始化,只存储一个包含用户所在状态的字符串变量。
更新以下代码现在可以正常工作了....
这是.h
#import <Foundation/Foundation.h>
#import "CJSONDeserializer.h"
@interface StateFinder : NSObject
{
NSString *userState;
NSURLConnection *connection;
}
-(id)initwithLatitude:(NSString *)latitude andLongitude:(NSString *)longitude;
@property (nonatomic, retain) NSString *userState;
@property (nonatomic, retain) NSURLConnection *connection;
@end
和.m
#import "StateFinder.h"
@implementation StateFinder
@synthesize userState;
@synthesize connection;
-(id)initwithLatitude:(NSString *)latitude andLongitude:(NSString *)longitude
{
if(self = [super init])
{
NSString *lat = latitude;
NSString *lon = longitude;
NSString *stateURLFinder = [NSString stringWithFormat:@"http://where.yahooapis.com/geocode?q=%@,+%@&gflags=R&flags=J&appid=zqoGxo7k", lat, lon];
//NSLog(stateURLFinder);
NSURL *stateURL = [NSURL URLWithString:stateURLFinder];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: stateURL];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
}
return self;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"didFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(jsonString);
// Yes, this is incomplete, but I was waiting for the method to fire before going
// any further. This will at least show me the JSON data being returned from yahoo
// in string format so I can output it to the console via NSLog
}
- (void)dealloc
{
[userState release];
[connection release];
[super dealloc];
}
@end
这是我正在使用的当前代码,它运行良好。我所做的只是在原始代码中包含 connectionDidFinishLoading 和 didFailWithError 方法。关于在建立之前释放的连接,我使用上面的代码没有前面提到的方法,并且 didReceiveData/didReceiveResponse 都不会命中。直到这两个方法被包含在内,这些方法才开始被调用。不知道如何,不知道为什么,但这是所有建议中唯一有效的变化。非常感谢@Jiva DeVoe、@XJones、@jlehr 和@Aby 提供的所有提示/提示/建议!
【问题讨论】:
-
根据多个建议,我注释掉了连接的释放,即使它似乎在用于调用我的数据库的代码的其他部分中工作。通过注释掉这个版本,我仍然没有在这个类中使用 didReceiveData 或 didReceiveResponse 方法。还有其他建议吗?
标签: objective-c nsurlconnection