如何等待Alamofire请求完成

时间:2016-12-14 12:52:31

标签: ios alamofire completionhandler

我正在进行网络API呼叫。我通过调用helper类中的post方法从我的类调用。所以我想将我在辅助类(alamofire响应)中收到的响应返回给完成请求的类。

MyClass的

 static func postMethodRequest(parameters:Parameters, methodName:String) -> [String:Any]
{
    let headers:HTTPHeaders = generateHeaders(methodType: "POST", methodName: methodName)

    var responseDictionary:[String: Any] = ["OperationStatus":"Success"]

   Alamofire.request("http:acaapi.idyas.net" + methodName, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON{ response in

        //This control comes to this block after a delay i.e., once the response is received.  

        responseDictionary = response.result.value as! [String: Any]

        print(responseDictionary)

    }

    return responseDictionary // This line of code does not wait for the response to be received. Hence the control goes to MyClass before the response is received.

}

WebServiceHelper:

<?php

namespace Http\Controllers;
use App\Http\Requests;
use App\Http\Requests\PrepareNoticeRequest;
use App\Provider;
use Illuminate\Http\Request;

class NoticesController extends Controller {

    public function create() {
        $providers = Provider::lists('name' , 'id');
        return view('notices.create' , compact('providers'));
    }

}

我希望该方法仅在收到响应后才返回responseDictionary。这可以通过Dispatchqueue或任何其他方式实现吗?

编辑:邓肯:我试着在这里理解这个问题。我想将响应返回给另一个类。它不仅仅是在alamofire响应块中调用一个函数。我无法将'return responseDictionary'代码放在块中。但我需要的是,我想在收到回复后返回responseDictionary。

0 个答案:

没有答案