此刻,我正在使用虚幻引擎的HTTP模块,并编写了一个类来从Web服务中查询天气信息。 首先,我创建了一个通用的HTTP服务类,如下所示:
#pragma once
#include "CoreMinimal.h"
#include "Runtime/Online/HTTP/Public/Http.h"
#include "Json.h"
#include "HTTPService.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FHTTPOnResponseRecievedDelegate, const FString&, HttpData);
UCLASS()
class THMVRAYPLUGIN_API UHTTPService : public UClass
{
GENERATED_BODY()
private:
FHttpModule * Http;
FString AuthorizationHeader = "Authorization";
void SetAuthorizationHash(FString Hash, TSharedRef<IHttpRequest>& Request);
void SetRequestHeaders(TSharedRef<IHttpRequest>& Request);
bool ResponseIsValid(FHttpResponsePtr Response, bool bWasSuccessful);
virtual void OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccesful);
void Send(TSharedRef<IHttpRequest>& Request);
public:
UHTTPService();
FHTTPOnResponseRecievedDelegate responseReceived;
TSharedRef<IHttpRequest> GetRequest(FString request);
};
我为OnResponseReceived事件声明了一个动态多播委托。 此方法广播接收到的JSON字符串:
void UHTTPService::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccesful)
{
if (ResponseIsValid(Response, bWasSuccesful)) {
FString JSONString = Response->GetContentAsString();
UE_LOG(LogTemp, Warning, TEXT("Http Response: %s"), *JSONString);
responseReceived.Broadcast(JSONString);
}
}
之后,我为特定的Web API创建了HTTPService类的子类:
#pragma once
#include "CoreMinimal.h"
#include "HTTPService.h"
#include "HTTPWeatherService.generated.h"
UCLASS()
class THMVRAYPLUGIN_API UHTTPWeatherService : public UHTTPService
{
GENERATED_BODY()
private:
FString APIBaseURL = "xxxx";
FString APIKey = "xxxx";
public:
UHTTPWeatherService();
void queryWeatherAPIForCoords(float lat, float lon);
};
现在,我想将其用于我编写的自定义演员。 在详细信息面板自定义中,我创建了一个自定义行来容纳这样的按钮:
//....
auto OnWeatherButtonClicked = [myActor]
{
float lat = myActor->latitude;
float lon = myActor->longitude;
UHTTPWeatherService * weatherService = NewObject<UHTTPWeatherService>();
weatherService->queryWeatherAPIForCoords(lat, lon);
return FReply::Handled();
};
experimentalGroup.AddWidgetRow()
.ValueContent()
[
SNew(SButton)
.Text(LOCTEXT("Current weather", "Get weather at current location"))
.ToolTipText(LOCTEXT("Uses a web api to get information on the current weather at the current coords","Uses a web api to get information on the current weather at the current coords"))
.OnClicked_Lambda(OnWeatherButtonClicked)
];
//...
单击按钮时,它会触发查询Web api的功能。 我现在想做的是将一个函数绑定到动态多播委托。 我想在收到响应时触发自定义角色的方法。 你会怎么做?什么是好的程序结构? 有人可以提供一段代码作为参考吗?
预先感谢=)
答案 0 :(得分:0)
我设法使其使用DECLARE_MULTICAST_DELEGATE_OneParam
而不是DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam
。