Files
2024-07-02 17:55:25 +02:00

194 lines
7.3 KiB
Objective-C

//
// ServerRequest.m
// Earthquake Network
//
// Refactored by Andrea Busi on 25/09/2020.
// Copyright © 2020 Earthquake Network. All rights reserved.
//
#import "ServerRequest.h"
#import "Reachability.h"
#import "Costanti.h"
#import "EQNUtility.h"
#import "NSDictionary+EQNExtensions.h"
@interface ServerRequest ()
@property (strong, nonatomic) NSURLSession *session;
@property (nonatomic) Reachability *internetReachability;
@end
@implementation ServerRequest
#pragma mark - Singleton
+ (instancetype)defaultServerConnectionSingleton
{
static ServerRequest *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
#pragma mark - Init
- (instancetype)init
{
self = [super init];
if (self) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:config];
// registro notifiche rilevamento connessione
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
[self setValue:@([self updateConnectionReachability:self.internetReachability]) forKey:@"isConnect"];
}
return self;
}
#pragma mark - Reachability notifications
/// Called by Reachability whenever status changes.
- (void)reachabilityChanged:(NSNotification *)notification
{
if ([notification.object isKindOfClass:[Reachability class]]) {
Reachability *curReach = [notification object];
[self setValue:@([self updateConnectionReachability:curReach]) forKey:@"isConnect"];
}
}
#pragma mark - Private
- (BOOL)updateConnectionReachability:(Reachability *)reachability
{
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus) {
case NotReachable: return NO;
default: return YES;
}
}
#pragma mark - Public
- (void)inviaInformazioniAlServerWithURL:(NSURL *)url richiesta:(EQNTipoChiamata)chiamata success:(successCompletionHandler)onSuccess failure:(errorCompletionHandler)onFailure
{
if (!self.isConnect) {
NSLog(@"[ServerRequest] not connected, return error");
NSError *error = [NSError errorWithDomain:NSMachErrorDomain code:401 userInfo:@{MESSAGGIO : NSLocalizedString(@"manual_error", @"")}];
onFailure(error);
// todo Andrea: perchè non viene fatto return? era già così
}
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"GET"];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
if (error) {
NSLog(@"[ServerRequest] response error: %@", error.localizedDescription);
onFailure(error);
return;
}
NSError *jsonError;
id JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
if (!jsonError){
if (EQNDebugPrintResponse) {
NSLog(@"[ServerRequest] response json: %@", JSON);
}
switch (httpResp.statusCode) {
case 200:
switch (chiamata) {
case EQNTipoChiamataPosizione:
onSuccess(@"success");
break;
case EQNTipoChiamataAlertSimulator:
onSuccess([NSString stringWithFormat:@"%@", JSON]);
break;
default:
onSuccess(JSON);
break;
}
}
} else {
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (newStr && (httpResp.statusCode >= 200 && httpResp.statusCode <= 299)) {
if (EQNDebugPrintResponse) {
NSLog(@"[ServerRequest] response string: %@", newStr);
}
switch (chiamata) {
case EQNTipoChiamataSegnalazioneTerremoto:
onSuccess([EQNUtility clearStringMessaggi:newStr]);
break;
case EQNTipoChiamataRilevamento:
onSuccess([EQNUtility clearStringMessaggi:newStr]);
break;
case EQNTipoChiamataPosizione:
case EQNTipoChiamataCalibrazione:
case EQNTipoChiamataImpostazioniNotifiche:
case EQNTipoChiamataAlertSimulator:
case EQNTipoChiamataAlertPushTest:
case EQNTipoChiamataRegisterSubscription:
onSuccess(newStr);
default:
// don't call the callback
break;
}
} else {
NSLog(@"[ServerRequest] Unable to create string with response: %@", [jsonError description]);
NSError *error = [NSError errorWithDomain:NSMachErrorDomain code:0 userInfo:@{MESSAGGIO : NSLocalizedString(@"manual_error", @"messaggio errore inserimento credenziali")}];
onFailure(error);
}
}
}];
[dataTask resume];
}
- (void)inviaRicevuta:(NSData *)ricevuta success:(successCompletionHandler)onSuccess failure:(errorCompletionHandler)onFailure
{
NSString *jsonObjectString = [ricevuta base64EncodedStringWithOptions:0];
NSDictionary *params = @{@"ricevuta" :jsonObjectString};
NSString *parametri = [params eqn_jsonStringWithPrettyPrint:YES];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setHTTPBody:[parametri dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
if (error) {
NSLog(@"[ServerRequest] inviaRicevuta | response error: %@", error.localizedDescription);
onFailure(error.userInfo[@"NSLocalizedDescription"]);
return;
}
NSError *jsonError;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
if (!jsonError) {
switch (httpResp.statusCode) {
case 200:
onSuccess(JSON);
break;
default:
NSLog(@"[ServerRequest] inviaRicevuta | response error, status code: %ld", (long)httpResp.statusCode);
break;
}
}
}];
[dataTask resume];
}
@end