将API连接调用分解为函数Objective-C

时间:2013-01-23 16:19:32

标签: objective-c function methods

这很可能是一个非常微不足道的问题,但我有一个连接设置为API以检索信息。现在我在viewDidLoad中设置了所有内容。我知道有一种更有效的方法来放置这些信息供用户以后访问,但我对Objective-C缺乏经验,知道如何操作。以下是我现在所有这些内容。

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.myurl.com"]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    NSData *myResponse = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];

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

    SBJsonParser *myParser = [[SBJsonParser alloc] init];

    NSArray *myData = [parser objectWithString:myString error:nil];

2 个答案:

答案 0 :(得分:1)

试试这个:

- (void)loadAndParseURL:(NSString *)URLString
             completion:(void (^)(NSArray *data))completion {

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    dispatch_async(dispatch_get_global_queue(DISPATH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      NSData *myResponse = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];

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

      SBJsonParser *myParser = [[SBJsonParser alloc] init];

      NSArray *myData = [parser objectWithString:myString error:nil];
      completion(myData);
    });
}

completion是一个块(匿名函数指针),它接受一个数组作为参数并执行自定义代码块。该块保存局部变量的值,即“环境”,并在执行时评估其内容(通常具有某种延迟),在此示例中,在myData从{{1}解析后}}。 myString放置发送请求的匿名块,并将其他内容放到后台队列中(当然是在后台线程中)。因此,在收到响应之前返回对此方法的调用,并且您应该在dispatch_async块之后安排任何内容。

答案 1 :(得分:0)

如果要将它旋转到线程中,那么您将使用sendAsynchronousRequest

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
   NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   SBJsonParser *myParser = [[SBJsonParser alloc] init];

    NSArray *myData = [parser objectWithString:myString error:nil];

   // Do what you want with the response and subscribe 
   //anywhere in your code to get notified when it completed.
   [[NSNotificationCenter defaultCenter] 
          postNotificationName:@"NotifyMeWhenDone" 
                        object:self];

}];