0

リクエストがafnetworkingで処理されるのを待つことができるかどうか疑問に思っていました.

このメソッドを取得したとしましょう

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    //Request goes here, so the method doesn't return anything before it's processed
}

それは可能ですか?

4

4 に答える 4

1

これは、同期要求と呼ばれます。

メソッドがメイン スレッドで呼び出されると、アプリがフリーズしたように見えるため、ネットワーキングを行う方法としては推奨されません。

それでもやりたい場合は、私がコメントしただまされた質問を参照して、それを行う方法の詳細を確認してください。

于 2013-09-18T19:02:12.853 に答える
1

可能ですが、何らかの非同期操作が完了するまでメイン キューを待機させたくありません。非同期操作が完了した後に何かを発生させたい場合は、AFNetworkingsuccessブロックを使用して、操作が完了したときに発生させたいことを指定する必要があります。

したがって、呼び出し元に へのポインターを提供する場合は、戻り値の型を にするのMWPhotoではなく、戻り値の型をMWPhoto *にしますvoidが、終了時に呼び出し元がそれを処理できるように完了ブロックを指定します。

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index completion:(void (^)(MWPhoto *))completion
{
    if (index < self.images.count) {

        GalleryPicture *thumbnail = [images objectAtIndex:index];
        NSURLResponse *response = nil;
        NSError *error = nil;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", API_URL, @"galleryPicture"]];

        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:gallery.objectId, @"galleryId", thumbnail.objectId, @"id", [NSNumber numberWithBool:NO], @"thumbnail", nil];
        ViveHttpClient *httpClient = [[ViveHttpClient alloc] initWithBaseURL:url];
        httpClient.parameterEncoding = AFFormURLParameterEncoding;
        NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:[url path] parameters:params];

        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            GalleryPicture *picture = [[GalleryPicture alloc] initWithJSON:JSON];
            completion([picture mwPhoto]);
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            // handle the error here
        }];

        // start your operation here
    }
}

したがって、ではなく:

MWPhoto *photo = [object photoBrowser:photoBrowser photoAtIndex:index];
// do whatever you want with `photo` here

代わりに次のようにすることもできます:

[object photoBrowser:photoBrowser photoAtIndex:index completion:^(MWPhoto *photo){
    // do whatever you want with `photo` here
}];
于 2013-09-18T19:04:53.787 に答える
0

AFURLConnectionOperation は NSOperation を継承しているため、NSOperation の waitUntilFinished メソッドを使用して、操作の終了を待つことができます。

ただし、AFURLConnectionOperation の成功ブロックと失敗ブロックは、waitUntilFinished が完了する前に実行されます。それでも、waitUntilFinished が完了した後、AFURLConnectionOperation の応答およびエラー プロパティにアクセスできます。

于 2013-09-18T19:03:49.133 に答える