帮助在自定义类中创建NSURLConnection
|
嘿,我正在尝试使用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
还有他们
#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方法包含到原始代码中。关于在建立连接之前将其释放的问题,我按原样使用上面的代码,而没有前面提到的方法,ReceiveData / didReceiveResponse都不会起作用。直到包括这两种方法时,这些方法才开始被调用。不确定如何,不确定为什么,但这是所有建议中起作用的唯一更改。非常感谢@Jiva DeVoe,@XJones,@jlehr和@Aby提供的所有提示/提示/建议!
没有找到相关结果
已邀请:
4 个回复
岭取
导力疵谜
消息,否则连接将无法运行。不要那样做。关于JSON,您说的从服务器返回的字符串是JSON。您还期待其他吗?
贸会
使用请求初始化连接后,它将自动运行。您还有其他问题。您对NSURLConnectionDelegate协议的实现是错误的。您需要将在“ 4”中接收的数据递增地添加到NSMutableData对象。您可以在“ connectionDidFinishLoading:\”中将其转换为JSON。 至于内存泄漏,请以
或
的方式释放连接。一定会收到一个,但不能同时收到。 您需要知道的一切都在这里 [编辑:添加了NSURLConnection代码示例]
恋卡
或
这两种方法,,10ѭ和
都开始被使用。谢谢大家的提示,建议和建议,希望这对以后的人有所帮助。