4

だから私はプロジェクトのために 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:' メソッドが 'void' を返すため、最後の行でエラーが発生します。

また、この記事を発見した後、「return」ステートメントをブロックの外に配置し、コードのブロック セクションの実行をロックしようとしました: http://omegadelta.net/2011/05/10/how-to-wait- for-ios-methods-with-completion-blocks-to-finish

まだ運がありません。

誰かがこの方法でそれを行う方法に光を当てることができることを願っています(または、データを返すためのより良い方法を提案するかもしれません)。

4

2 に答える 2

8

ブロックを使って応答を返してみませんか?何かのようなもの:

-(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);
    }];
}
于 2012-08-23T16:17:14.963 に答える
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];
    });
});
于 2012-08-23T18:49:57.150 に答える