等待请求被处理 [英] Waiting for request to be processed

查看:155
本文介绍了等待请求被处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以等待通过afnetworking处理请求。

I was wondering if I could wait for request to be processed with afnetworking.

让我说我有这种方法

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

这可行吗?

推荐答案

可以,但是您永远不希望主队列等待某些异步操作完成。如果希望在异步操作完成后发生某些事情,则应使用AFNetworking 成功块指定操作完成后要发生的事情。

You can, but you never want the main queue waiting for some asynchronous operation to complete. If you want something to happen after your asynchronous operation is done, you should use the AFNetworking success block to specify what you want to happen when the operation is done.

因此,如果要为调用者提供指向 MWPhoto 的指针,而不是返回类型为 MWPhoto * ,返回类型为 void ,但是提供了一个完成块,以便调用者可以在完成时处理它:

So, if you want to provide the caller a pointer to the MWPhoto, rather than having a return type of MWPhoto *, have a return type of void, but supply a completion block so that the caller can handle it when it's done:

- (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
}];

这篇关于等待请求被处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆