Hello everyone and Happy New Year!
I'm stuck with a problem. I'm making a project game in UE5 and making an ammo box for my tank to get additional ammo. I made a class AmmoBox:
AmmoBox.h
#pragma once
#include "Cannon.h"
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "AmmoBox.generated.h"
UCLASS()
class TANKOGEDDON_API AAmmoBox : public AActor
{
GENERATED_BODY()
public:
AAmmoBox();
protected:
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite, Category = "Components")
UStaticMeshComponent* Mesh;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Ammo")
TSubclassOf<ACannon> CannonClass;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Ammo")
int additionalAmmo = 5;
UFUNCTION()
void OnMeshOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const
FHitResult& SweepResult);
AmmoBox.cpp
#include "AmmoBox.h"
#include "TankPawn.h"
#include "Components/StaticMeshComponent.h"
#include "Engine/World.h"
#include "GameFramework/PlayerController.h"
// Sets default values
AAmmoBox::AAmmoBox()
{
PrimaryActorTick.bCanEverTick = false;
USceneComponent * sceneCpm = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
RootComponent = sceneCpm;
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
Mesh->SetupAttachment(RootComponent);
Mesh->OnComponentBeginOverlap.AddDynamic(this, &AAmmoBox::OnMeshOverlapBegin);
Mesh->SetCollisionProfileName(FName("OverlapAll"));
Mesh->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
Mesh->SetGenerateOverlapEvents(true);
}
void AAmmoBox::OnMeshOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
ATankPawn * TankPawn = Cast<ATankPawn>(OtherActor);
TSubclassOf<ACannon> testActor;
ACannon* Cannon = Cast<ACannon>(testActor);
if(TankPawn)
{
Cannon->AddAmmo(additionalAmmo);
TankPawn->SetFirstCannon(CannonClass);
TankPawn->SetupCannon(CannonClass);
Destroy();
}
}
And have another class Cannon that has an int variable EquippedAmmo and a method AddAmmo():
void ACannon::AddAmmo(int addedAmmo)
{
Ammo+=addedAmmo;
}
And I still don't understand casting to quite well. I'm trying to get the AddAmmo method in the AmmoBox.cpp in OnMeshOverlapBegin function to add ammo to my cannon. And Compiler doesn't show any issues. But whenever I overlap an ammobox with my tank the game instantly crashes. This is what I get:
=== Critical error: ===
Error LogWindows Fatal error!
Error LogWindows Unhandled Exception: EXCEPTION_ACCESS_VIOLATION writing address 0x0000000000000400
Error LogWindows [Callstack] 0x00007ffbb2413250 UnrealEditor-Tankogeddon.dll!ACannon::AddAmmo() [D:\GeekBrains\UE Course\Tankogeddon\Tankogeddon\Source\Tankogeddon\Cannon.cpp:155]
Error LogWindows [Callstack] 0x00007ffbb24124f8 UnrealEditor-Tankogeddon.dll!AAmmoBox::OnMeshOverlapBegin() [D:\GeekBrains\UE Course\Tankogeddon\Tankogeddon\Source\Tankogeddon\AmmoBox.cpp:37]
Error LogWindows [Callstack] 0x00007ffbb2418e27 UnrealEditor-Tankogeddon.dll!AAmmoBox::execOnMeshOverlapBegin() [D:\GeekBrains\UE Course\Tankogeddon\Tankogeddon\Intermediate\Build\Win64\UnrealEditor\Inc\Tankogeddon\AmmoBox.gen.cpp:35]
Error LogWindows [Callstack] 0x00007ffc21f1bc07 UnrealEditor-CoreUObject.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc22141837 UnrealEditor-CoreUObject.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd34e03f4 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd33998fb UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd3a47e9d UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd3a4761d UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd3a94646 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd3a75caa UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd34f08ff UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbb2418504 UnrealEditor-Tankogeddon.dll!ATankPawn::Tick() [D:\GeekBrains\UE Course\Tankogeddon\Tankogeddon\Source\Tankogeddon\TankPawn.cpp:70]
Error LogWindows [Callstack] 0x00007ffbd34f82b2 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd34bea96 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd4fd5a0f UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd4fdccf8 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc1f783a9d UnrealEditor-Core.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc1f783f3e UnrealEditor-Core.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc1f78d6af UnrealEditor-Core.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd4ff2f0a UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd4ff98b0 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd403f08f UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffbd40479c0 UnrealEditor-Engine.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc1d5de5f5 UnrealEditor-UnrealEd.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc1df6aac6 UnrealEditor-UnrealEd.dll!UnknownFunction []
Error LogWindows [Callstack] 0x00007ff71ef082f6 UnrealEditor.exe!UnknownFunction []
Error LogWindows [Callstack] 0x00007ff71ef20d9c UnrealEditor.exe!UnknownFunction []
Error LogWindows [Callstack] 0x00007ff71ef20e8a UnrealEditor.exe!UnknownFunction []
Error LogWindows [Callstack] 0x00007ff71ef23c4d UnrealEditor.exe!UnknownFunction []
Error LogWindows [Callstack] 0x00007ff71ef35564 UnrealEditor.exe!UnknownFunction []
Error LogWindows [Callstack] 0x00007ff71ef38736 UnrealEditor.exe!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc768355a0 KERNEL32.DLL!UnknownFunction []
Error LogWindows [Callstack] 0x00007ffc7804485b ntdll.dll!UnknownFunction []
Log LogExit Executing StaticShutdownAfterError
Cannon.h
#pragma once
#include "CoreMinimal.h"
#include "GameStructs.h"
#include "GameFramework/Actor.h"
#include "Cannon.generated.h"
UCLASS()
class TANKOGEDDON_API ACannon : public AActor
{
GENERATED_BODY()
public:
ACannon();
void Fire();
void SpecialFire();
void Reload();
void ReloadSpecial();
bool IsReadyToFire();
bool IsReadyToFireSpecial();
void AddAmmo(int32 addedAmmo);
FTimerHandle ReloadTimer;
FTimerHandle ReloadTimerSpecial;
protected:
virtual void BeginPlay() override;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Components")
class UStaticMeshComponent* CannonMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Components")
class UArrowComponent* ProjectileSpawnPoint;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components")
TSubclassOf<class AProjectile> ProjectileClass;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components")
ECannonType CannonType = ECannonType::FireProjectile;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Fire params")
float FireRate = 1.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Fire params")
float FireRange = 1000.0f;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Fire params")
float FireDamage = 1.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Fire params")
int Ammo = 10;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Fire params")
int SpecialAmmo = 4;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Fire params")
float SpecialFireRate = 0.3f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Fire params")
int SpecialFireProjectilesQty = 4;
private:
bool bReadyToFire = false;
bool bReadyToFireSpecial = false;
};
Cannon.cpp
#include "Cannon.h"
#include "Projectile.h"
#include "Components/ArrowComponent.h"
#include "Components/StaticMeshComponent.h"
#include "TimerManager.h"
#include "Engine/Engine.h"
ACannon::ACannon()
{
PrimaryActorTick.bCanEverTick = false;
USceneComponent* sceneComp = CreateDefaultSubobject<USceneComponent>(TEXT("SceneRoot"));
RootComponent = sceneComp;
CannonMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("CannonMesh"));
CannonMesh->SetupAttachment(sceneComp);
ProjectileSpawnPoint = CreateDefaultSubobject<UArrowComponent>(TEXT("ProjectileSpawnPoint"));
ProjectileSpawnPoint->SetupAttachment(CannonMesh);
}
void ACannon::BeginPlay()
{
Super::BeginPlay();
Reload();
ReloadSpecial();
}
void ACannon::Fire()
{
if(!IsReadyToFire())
{
return;
}
bReadyToFire = false;
Ammo--;
if(CannonType == ECannonType::FireProjectile)
{
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Red, \
FString::Printf(TEXT("Fire projectile. %d ammo left"), Ammo));
AProjectile* projectile = GetWorld()->SpawnActor<AProjectile>(ProjectileClass,
ProjectileSpawnPoint->GetComponentLocation(), ProjectileSpawnPoint->GetComponentRotation());
if(projectile)
{
projectile->Start();
}
}
else
{
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Red, FString::Printf(TEXT("Fire trace")));
FHitResult hitResult;
FCollisionQueryParams traceParams = FCollisionQueryParams(FName(TEXT("FireTrace")), true, this);
traceParams.bTraceComplex = true;
traceParams.bReturnPhysicalMaterial = false;
FVector Start = ProjectileSpawnPoint->GetComponentLocation();
FVector End = Start + ProjectileSpawnPoint->GetForwardVector() * FireRange;
if(GetWorld()->LineTraceSingleByChannel(hitResult, Start, End, ECC_Visibility, traceParams))
{
DrawDebugLine(GetWorld(), Start, hitResult.Location, FColor::Purple, false, \
1.0f, 0, 5.0f);
if(hitResult.GetActor())
{
UE_LOG(LogTemp,Warning, TEXT("trace overlap : %s"), *hitResult.GetActor()->GetName());
hitResult.GetActor()->Destroy();
}
}
else
{
DrawDebugLine(GetWorld(), Start, End, FColor::Red, false, \
1.0f, 0, 5.0f);
}
}
GetWorld()->GetTimerManager().SetTimer(ReloadTimer, this, &ACannon::Reload, 1/FireRate, false);
}
void ACannon::SpecialFire()
{
if(!IsReadyToFireSpecial())
{
return;
}
bReadyToFireSpecial = false;
SpecialAmmo --;
if(CannonType == ECannonType::FireProjectile)
{
for(int i = 0; i < SpecialFireProjectilesQty; i++)
{
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Blue, \
FString::Printf(TEXT("Special fire!")));
}
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Blue, \
FString::Printf(TEXT(" %d special ammo left"), SpecialAmmo));
}
else
{
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Blue, FString::Printf(TEXT("Fire trace")));
}
GetWorld()->GetTimerManager().SetTimer(ReloadTimerSpecial, this, &ACannon::ReloadSpecial, 1/SpecialFireRate, false);
}
void ACannon::Reload()
{
bReadyToFire = true;
if(Ammo <=0)
{
bReadyToFire = false;
}
}
void ACannon::ReloadSpecial()
{
bReadyToFireSpecial = true;
if(SpecialAmmo <=0)
{
bReadyToFireSpecial = false;
GEngine->AddOnScreenDebugMessage(-1, 2.0f, FColor::Blue, FString::Printf(TEXT("No Special Ammo")));
}
}
bool ACannon::IsReadyToFire()
{
return bReadyToFire;
}
bool ACannon::IsReadyToFireSpecial()
{
return bReadyToFireSpecial;
}
void ACannon::AddAmmo(int addedAmmo)
{
Ammo+=addedAmmo;
}
Related
Be gladfull about any info about how to add client p12 certificate validation to this ssl pinning code. This is part of ssl pinning module for react-native.
#import "RNSslPinning.h"
#import "AFNetworking.h"
#interface RNSslPinning()
#property (nonatomic, strong) NSURLSessionConfiguration *sessionConfig;
#end
#implementation RNSslPinning
RCT_EXPORT_MODULE();
- (instancetype)init
{
self = [super init];
if (self) {
self.sessionConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration];
self.sessionConfig.HTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
}
return self;
}
RCT_EXPORT_METHOD(getCookies: (NSURL *)url resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
NSHTTPCookie *cookie;
NSHTTPCookieStorage* cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage;
NSMutableDictionary* dictionary = #{}.mutableCopy;
for (cookie in [cookieJar cookiesForURL:url]) {
[dictionary setObject:cookie.value forKey:cookie.name];
}
if ([dictionary count] > 0){
resolve(dictionary);
}
else{
NSError *error = nil;
reject(#"no_cookies", #"There were no cookies", error);
}
}
RCT_EXPORT_METHOD(removeCookieByName: (NSString *)cookieName
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookieStorage.cookies) {
// [cookieStorage deleteCookie:each];
NSString * name = cookie.name;
if([cookieName isEqualToString:name]) {
[cookieStorage deleteCookie:cookie];
}
}
resolve(nil);
}
-(void)performRequest:(AFURLSessionManager*)manager obj:(NSDictionary *)obj request:(NSMutableURLRequest*) request callback:(RCTResponseSenderBlock) callback {
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSString *bodyString = [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding];
NSInteger statusCode = httpResp.statusCode;
if (!error) {
// if(obj[#"responseType"]){
NSString * responseType = obj[#"responseType"];
if ([responseType isEqualToString:#"base64"]){
NSString* base64String = [responseObject base64EncodedStringWithOptions:0];
callback(#[[NSNull null], #{
#"status": #(statusCode),
#"headers": httpResp.allHeaderFields,
#"data": base64String
}]);
}
else {
callback(#[[NSNull null], #{
#"status": #(statusCode),
#"headers": httpResp.allHeaderFields,
#"bodyString": bodyString ? bodyString : #""
}]);
}
} else if (error && error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]) {
dispatch_async(dispatch_get_main_queue(), ^{
callback(#[#{
#"status": #(statusCode),
#"headers": httpResp.allHeaderFields,
#"bodyString": bodyString ? bodyString : #""
}, [NSNull null]]);
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
callback(#[error.localizedDescription, [NSNull null]]);
});
}
}] resume];
}
-(void) setHeaders: (NSDictionary *)obj request:(NSMutableURLRequest*) request {
if (obj[#"headers"] && [obj[#"headers"] isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *m = [obj[#"headers"] mutableCopy];
for (NSString *key in [m allKeys]) {
if (![m[key] isKindOfClass:[NSString class]]) {
m[key] = [m[key] stringValue];
}
}
[request setAllHTTPHeaderFields:m];
}
}
- (BOOL) isFilePart: (NSArray*)part {
if (![part[1] isKindOfClass:[NSDictionary class]]) {
return NO;
}
NSDictionary * value = part[1];
return [value objectForKey:#"type"] && ([value objectForKey:#"name"] || [value objectForKey:#"fileName"]);
}
-(void) appendFormDataFilePart: (id<AFMultipartFormData>) formData fileData: (NSArray*) fileData {
NSString * key = fileData[0];
NSDictionary * value = fileData[1];
NSString * fileName = [value objectForKey:#"name"] ? [value objectForKey:#"name"] : [value objectForKey:#"fileName"];
NSString * mimeType = [value objectForKey:#"type"];
NSString * path = [value objectForKey:#"uri"] ? [value objectForKey:#"uri"] : [value objectForKey:#"path"];
[formData appendPartWithFileURL:[NSURL URLWithString:path] name:key fileName:fileName mimeType:mimeType error:nil];
}
-(void) performMultipartRequest: (AFURLSessionManager*)manager obj:(NSDictionary *)obj url:(NSString *)url request:(NSMutableURLRequest*) request callback:(RCTResponseSenderBlock) callback formData:(NSDictionary*) formData {
NSString * method = obj[#"method"] ? obj[#"method"] : #"POST";
NSMutableURLRequest *formDataRequest = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:method URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _formData) {
if([formData objectForKey:#"_parts"]){
NSArray * parts = formData[#"_parts"];
for (int i = 0; i < [parts count]; i++)
{
NSArray * part = parts[i];
NSString * key = part[0];
if ([self isFilePart:part]) {
[self appendFormDataFilePart:_formData fileData: part];
} else {
NSString * value = part[1];
NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
[_formData appendPartWithFormData:data name: key];
}
}
}
} error:nil];
// Migrate header fields.
[formDataRequest setAllHTTPHeaderFields:[request allHTTPHeaderFields]];
NSURLSessionUploadTask *uploadTask = [manager
uploadTaskWithStreamedRequest:formDataRequest
progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Upload progress %lld", uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSString *bodyString = [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding];
NSInteger statusCode = httpResp.statusCode;
if (!error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSString *bodyString = [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding];
NSInteger statusCode = httpResp.statusCode;
NSDictionary *res = #{
#"status": #(statusCode),
#"headers": httpResp.allHeaderFields,
#"bodyString": bodyString ? bodyString : #""
};
callback(#[[NSNull null], res]);
}
else if (error && error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]) {
dispatch_async(dispatch_get_main_queue(), ^{
callback(#[#{
#"status": #(statusCode),
#"headers": httpResp.allHeaderFields,
#"bodyString": bodyString ? bodyString : #""
}, [NSNull null]]);
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
callback(#[error.localizedDescription, [NSNull null]]);
});
}
}];
[uploadTask resume];
}
RCT_EXPORT_METHOD(fetch:(NSString *)url obj:(NSDictionary *)obj callback:(RCTResponseSenderBlock)callback) {
NSURL *u = [NSURL URLWithString:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:u];
AFSecurityPolicy *policy;
BOOL pkPinning = [[obj objectForKey:#"pkPinning"] boolValue];
BOOL disableAllSecurity = [[obj objectForKey:#"disableAllSecurity"] boolValue];
NSSet *certificates = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
// set policy (ssl pinning)
if(disableAllSecurity){
policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
policy.validatesDomainName = false;
policy.allowInvalidCertificates = true;
}
else if (pkPinning){
policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:certificates];
}
else{
policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certificates];
}
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.securityPolicy = policy;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
if (obj[#"method"]) {
[request setHTTPMethod:obj[#"method"]];
}
if (obj[#"timeoutInterval"]) {
[request setTimeoutInterval:[obj[#"timeoutInterval"] doubleValue] / 1000];
}
if(obj[#"headers"]) {
[self setHeaders:obj request:request];
}
if (obj) {
if ([obj objectForKey:#"body"]) {
NSDictionary * body = obj[#"body"];
// this is a multipart form data request
if([body isKindOfClass:[NSDictionary class]]){
// post multipart
if ([body objectForKey:#"formData"]) {
[self performMultipartRequest:manager obj:obj url:url request:request callback:callback formData:body[#"formData"]];
} else if ([body objectForKey:#"_parts"]) {
[self performMultipartRequest:manager obj:obj url:url request:request callback:callback formData:body];
}
}
else {
// post a string
NSData *data = [obj[#"body"] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[self performRequest:manager obj:obj request:request callback:callback ];
//TODO: if no body
}
}
else {
[self performRequest:manager obj:obj request:request callback:callback ];
}
}
else {
}
}
+ (BOOL)requiresMainQueueSetup
{
return YES;
}
#end
All info, I've had found, is about to create some challenge to session and send client certificate with password from there.
But not sure how to implement this right way. And can't figure which version of AFNetworking used in this SSL Pinning module.
Here is the answer.
In "fetch" function, after "manager" decloration, use this code:
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing _Nullable * _Nullable credential) {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustResultType result;
SecTrustEvaluate(challenge.protectionSpace.serverTrust, &result);
// If we want to ignore invalid server for certificates, we just accept the server
if (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified) {
// When testing this against a trusted server I got kSecTrustResultUnspecified every time. But the other two match the description of a trusted server
*credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
}
return NSURLSessionAuthChallengeUseCredential;
}
if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
SecIdentityRef identity = NULL;
SecTrustRef trust = NULL;
NSString *p12 = [[NSBundle mainBundle] pathForResource:#"client"ofType:#"p12"]; //client cert
NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
OSStatus securityError = errSecSuccess;
NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:#"password" forKey:(__bridge id)kSecImportExportPassphrase]; //client cert password
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import((__bridge CFDataRef)PKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items);
if(securityError == 0) {
CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);
const void*tempIdentity =NULL;
tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);
identity = (SecIdentityRef)tempIdentity;
const void*tempTrust =NULL;
tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);
trust = (SecTrustRef)tempTrust;
}
SecCertificateRef certificate = NULL;
SecIdentityCopyCertificate(identity, &certificate);
const void*certs[] = {certificate};
CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
*credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
return NSURLSessionAuthChallengeUseCredential;
}
return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}];
I am running a unit test using PowerMockito to perform a query using Vert.x's CassandraClient and I see ClassCastException.
Similar code works when performing updates.
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(VertxUnitRunner.class)
#PowerMockIgnore("javax.management.*")
#PrepareForTest({ CassandraClient.class, ResultSet.class, Row.class })
class TestCassandraClient {
#Mock
private AsyncResult<List<Row>> asyncListRow;
#Mock
private List<Row> listRow;
#Test
public void testQueryKeyspaces(TestContext context) {
Mockito.when(asyncListRow.succeeded()).thenReturn(true);
Mockito.when(asyncListRow.result()).thenReturn(listRow);
Mockito.when(listRow.size()).thenReturn(0);
Mockito.doAnswer(new Answer<AsyncResult<List<Row>>>() {
#SuppressWarnings("unchecked")
#Override
public AsyncResult<List<Row>> answer(InvocationOnMock invocation) throws Throwable {
((Handler<AsyncResult<List<Row>>>) invocation.getArgument(1)).handle(asyncListRow);
return asyncListRow;
}
}).when(client).executeWithFullFetch(Mockito.anyString(), Mockito.any());
Async async = context.async(1);
try {
(new Operation()).queryAll(client, "SELECT * FROM system_schema.keyspaces")
.setHandler(ar -> {
if (ar.succeeded()) {
async.complete();
} else {
context.fail("Failed to perform operation");
}
});
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
context.verify(v -> {
Assert.fail(e.getMessage());
});
async.complete();
}
}
}
The method "queryAll" is as below:
Class Operation {
public Future<OperationResult> queryAll(#NonNull final CassandraClient client, #NonNull final String query) {
Objects.requireNonNull(client, "CassandraClient cannot be null");
Objects.requireNonNull(query, "Update query cannot be null");
Future<OperationResult> future = Future.future();
try {
client.executeWithFullFetch(query, rh -> {
OperationResult resultObj = new OperationResult();
if (rh.succeeded()) {
resultObj.setSuccess(true);
List<Row> rows = rh.result();
if (rows != null && rows.size() > 0) {
Row row = rows.get(0);
ColumnDefinitions colDefs = row.getColumnDefinitions();
resultObj.setColumnDefinitions(toJsonArray(colDefs));
}
resultObj.setData(toJsonArray(rows));
} else {
resultObj.setSuccess(false);
resultObj.setException(rh.cause().getMessage());
}
future.complete(resultObj);
});
} catch (Exception e) {
String msg = String.format("Problem invoking query: %s. Error: %s", query, e.getMessage());
LOGGER.error(msg, e);
OperationResult resultObj = new OperationResult();
resultObj.setSuccess(false);
resultObj.setException(msg);
future.complete(resultObj);
}
return future;
}
}
Note that I have added a mock instruction
to return zero rows
Mockito.when(listRow.size()).thenReturn(0);
So, In the first line you see the response is returning a list of zero rows, but next I see an error as below.
05:21:41.015 [vert.x-eventloop-thread-0] DEBUG c.b.t.p.c.api.beans.OperationResult - JSON representation: {"column-definitions":null,"rows":[],"success":true,"exception":null}
05:21:41.015 [vert.x-eventloop-thread-0] ERROR c.b.t.p.c.api.operation.Operation - Problem invoking query: SELECT * FROM system_schema.keyspaces. Error: io.vertx.core.AsyncResult$MockitoMock$1728182793 cannot be cast to io.vertx.cassandra.CassandraClient
java.lang.ClassCastException: io.vertx.core.AsyncResult$MockitoMock$1728182793 cannot be cast to io.vertx.cassandra.CassandraClient
at io.vertx.cassandra.CassandraClient$MockitoMock$873315432.executeWithFullFetch(Unknown Source)
at com.bmc.tso.persistence.client.api.operation.Operation.queryAll(Operation.java:195)
at com.bmc.tso.persistence.client.api.operation.KeyspaceOperationUnitTest.testQueryKeyspaces(KeyspaceOperationUnitTest.java:372)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at io.vertx.ext.unit.junit.VertxUnitRunner.invokeTestMethod(VertxUnitRunner.java:95)
at io.vertx.ext.unit.junit.VertxUnitRunner.lambda$invokeExplosively$0(VertxUnitRunner.java:114)
at io.vertx.ext.unit.impl.TestContextImpl.run(TestContextImpl.java:90)
at io.vertx.ext.unit.junit.VertxUnitRunner.lambda$invokeExplosively$1(VertxUnitRunner.java:127)
at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:320)
at io.vertx.core.impl.EventLoopContext.lambda$executeAsync$0(EventLoopContext.java:38)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:462)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:897)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
05:21:
I'm trying to run the below code :
func mapView(_ mapView: GMSMapView, didTapPOIWithPlaceID placeID: String, name: String, location: CLLocationCoordinate2D) {
print("You tapped \(name): \(placeID), \(location.latitude)/\(location.longitude)")
infoMarker.snippet = placeID
infoMarker.position = location
infoMarker.title = name
infoMarker.opacity = 0;
infoMarker.infoWindowAnchor.y = 1
infoMarker.map = mapView
mapView.selectedMarker = infoMarker
placesClient!.lookUpPlaceID(placeID, callback: { (place: GMSPlace?, error: NSError?) -> Void in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
if let place = place {
print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place placeID \(place.placeID)")
print("Place attributions \(place.attributions)")
} else {
print("No place details for \(placeID)")
}
} as! GMSPlaceResultCallback)
}
As soon as the lookUpPlaceID line runs, it throws the exception :
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Something like this should work for you:
placesClient.lookUpPlaceID(placeId, callback: { (place, error) -> Void in
if let error = error {
print("lookup place id query error: \(error.localizedDescription)")
return
}
if let place = place {
print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place placeID \(place.placeID)")
print("Place attributions \(place.attributions)")
} else {
print("No place details for \(placeID)")
}
})
I have this error when I run my unit test (assertEquals):
java.lang.AssertionError: expected:sun.security.ssl.SSLSocketFactoryImpl#48030df0> but was:sun.security.ssl.SSLSocketFactoryImpl#40882c7f>
when I run my unit test for this code to test getSslSocketFactory method
public ClientCertSocketFactory() throws IOException{
String trustStoreFilePath = System.getProperty("javax.net.ssl.trustStore");
try {
TrustManagerFactory trustManagerFactory = CertManagerFactory.loadTrustStore(trustStoreFilePath);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
this.sslSocketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
LOGGER.error("No Provider supports a TrustManagerFactorySpi implementation for the TLS protocol. Error message: " + e);
} catch (KeyManagementException e) {
LOGGER.error("Error occurred when initializing SSLContext. Error message: " + e);
}
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
My unit test for getSslSocketFactory is:
#Test
public void shouldGetSslSocketFactory() throws IOException, NoSuchAlgorithmException, KeyManagementException{
String trustStoreFilePath = System.getProperty("javax.net.ssl.trustStore");
TrustManagerFactory trustManagerFactory = CertManagerFactory.loadTrustStore(trustStoreFilePath);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
this.sslSocketFactory = sslContext.getSocketFactory();
assertEquals(sslSocketFactory, clientCertSocketFactory.getSslSocketFactory());
}
How I can fix it ?
Thanks a lot
When I am Fetching name and pic_square from my friend list the it shows the following error.
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
FBSDKLog: Error: HTTP status code: 400
FBSDKLog: Response <#1386> <Error>:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
{
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x146f1600, state: FBSessionStateOpen, loginHandler: 0x146cca50, appID: 293072694193895, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x1468b170>, expirationDate: 2014-07-17 07:47:12 +0000, refreshDate: 2014-05-18 11:14:42 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n status,\n permission\n)>";
"com.facebook.sdk:HTTPStatusCode" = 400;
"com.facebook.sdk:ParsedJSONResponseKey" = (
{
body = {
error = {
code = 606;
message = "(#606) The global ID 100003190599973 is not allowed. Please use the application specific ID instead.";
type = OAuthException;
};
};
code = 400;
}
);
}
here I used the code for retrieving the the required information
NSString *query = [NSString stringWithFormat:#"select name, pic_square from user where uid = %#", curId];
NSDictionary *queryParam = [NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql" parameters:queryParam HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
{
[namePicArray addObject:result[#"data"]];
}
}];
Thanks in advance.