2012-08-23 73 views
3

因此,我正在嘗試在Twitter API(針對某個項目)之上構建一個圖層,並且我需要找到一種方法將Twitter操作的結果返回到抽象層。完成塊的返回結果

現在我的設置是這樣的,例如:

-(NSDictionary *)sendTweet:(Tweet *)tweet { 
     __block NSMutableDictionary *responseDictionary; 

    NSLog(@"Sending tweet"); 

    NSMutableDictionary *twitterRequestDictionary = [[NSMutableDictionary alloc] init]; 
    [twitterRequestDictionary setObject:tweet.tweetBody forKey:@"status"]; 

    TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"] 
              parameters:twitterRequestDictionary 
              requestMethod:TWRequestMethodPOST]; 
    [request setAccount:self.userAccount]; 


    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { 
     responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; 
     NSLog(@"Response dictionary: %@", responseDictionary); 
     return responseDictionary; 
    }]; 

}

但由於「performRequestWithHandler:」方法返回「無效」我的最後一行導致錯誤。

我也試着放置「return」語句塊的外面,發現這篇文章後鎖定的代碼塊段的執行:http://omegadelta.net/2011/05/10/how-to-wait-for-ios-methods-with-completion-blocks-to-finish

仍然沒有運氣。

我希望有人可以通過這種方式來做到這一點(或者建議一種更好的方法來返回數據)。

回答

7

爲什麼你不使用塊返回響應?例如:

-(void)sendTweet:(Tweet *)tweet withResponseCallback:(void (^)(NSMutableDictionary *responseDictionary))callback { 

    NSLog(@"Sending tweet"); 

    NSMutableDictionary *twitterRequestDictionary = [[NSMutableDictionary alloc] init]; 
    [twitterRequestDictionary setObject:tweet.tweetBody forKey:@"status"]; 

    TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"] 
              parameters:twitterRequestDictionary 
              requestMethod:TWRequestMethodPOST]; 
    [request setAccount:self.userAccount]; 


    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { 
     NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; 
     NSLog(@"Response dictionary: %@", responseDictionary); 
     callback(responseDictionary); 
    }]; 
} 
+0

啊,這看起來像一個良好的開端。有什麼方法可以返回數據嗎?像,也許等到完成處理程序被調用,然後返回它?這一直讓我瘋狂! –

+1

你不想'sendTweet:'返回響應。否則,它將阻止Twitter請求期間的用戶界面,這可能是有損連接的幾分鐘。你需要看看你如何使用響應。一種常見的模式是讓回調塊顯示成功/錯誤消息,並且如果帖子成功,也許只有用推文正文清除文本視圖。 –

0

由於您使用的是異步方法,因此很難說您的方法何時會返回數據。所以你可以考慮其他選項來返回結果。例如,發佈通知,發送消息,設置某個屬性或甚至顯示警報視圖可能很有用。

至於文章」代碼示例我會嘗試像下面

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSData *data = [self loadDataWithConditionLock]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self updateUIWithData:data]; 
    }); 
}); 
相關問題