从网上从数据抓取类返回数据?

时间:2010-10-07 16:29:04

标签: iphone ios nsurlconnection

我正在尝试创建一个允许我从Web服务获取请求数据的类。我坚持如何返回值。

// FooClass.m
// DataGrabber is the class which is supposed to get values
dataGrabber = [[DataGrabber alloc] init];
xmlString = [dataGrabber getData:[NSDictionary dictionaryWithObjectsAndKeys:@"news", @"instruction", @"sport", @"section", nil]];

在这个例子中,它应该得到体育新闻。问题是DataGrabber异步获取数据并最终从几个NSURLConnection委托方法跳转。在收到数据时如何知道FooClass?

3 个答案:

答案 0 :(得分:3)

与严格协议一起使用的委托模式对此非常有用(这就是DataGrabber在NSURLConnection完成时会发现的,对吧?)。我编写了许多以这种方式使用XML和JSON信息的Web API。

// In my view controller
- (void) viewDidLoad
{
  [super viewDidLoad];
  DataGrabber *dataGrabber = [[DataGrabber alloc] init];
  dataGrabber.delegate = self;
  [dataGrabber getData:[NSDictionary dictionaryWithObjectsAndKeys:@"news", @"instruction", @"sport", @"section", nil]];
}

然后在DataGrabber.h文件中:

@protocol DataGrabberDelegate
@required
- (void) dataGrabberFinished:(DataGrabber*)dataGrabber;
- (void) dataGrabber:(DataGrabber*)dataGrabber failedWithError:(NSError*)error;
@end

在DataGrabber.m中:

- (void) getData:(NSDictionary*)dict
{
  // ... Some code to process "dict" here and create an NSURLRequest ...
  NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
}

- (void) connectionDidFinishLoading:(NSURLConnection*)connection
{
  // ... Do any processing with the returned data ...

  // Tell our view controller we are done
  [self.delegate dataGrabberFinished:self];
}

然后确保Foo实现DataGrabberDelegate协议方法来处理每个案例。

最后,您的DataGrabber具有delegate属性(请确保使用assign,而不是保留以避免保留周期):

@property (nonatomic, assign) id<DataGrabberDelegate> delegate;

当在DataGrabber内部完成NSURLConnection异步加载时,它们会在上面列出的协议中回调您的UIViewController,以便您可以更新UI。如果它是一个请求,理论上你可以摆脱DataGrabber并将它放在你的视图控制器中,但我喜欢“分离我的顾虑” - API和View Controller保持独立。它会生成一个额外的层,但它会将“文本处理代码”保留在视图控制器之外(特别是对于JSON和XML解析代码)。

我已经成功完成了很多次 - 另一个关键是向用户提供页面加载的一些反馈是好的 - 打开状态栏中的活动指示器,向他们显示UIActivityIndi​​cator等。 ,然后当你的委托回调成功或失败时,你就会摆脱它。

最后,我写了一篇更详细的博客文章:Consuming Web APIs on the iPhone

答案 1 :(得分:1)

您可以为您的DataGrabber课程实施通知,这些通知会在您收到一定数量的数据时(或者如果您需要完成下载时)关闭,然后是通知方法(请参阅文档中的通知)可以做任何你想要的处理。

注意:如果FooClassDataGrabber

的代表,那将会很有帮助

答案 2 :(得分:0)

我也使用通知。 Here is a good detailed explanation如何设置它。

相关问题