// // MBIMHTTPConnection.m // CocoaHTTPServer // // Created by James Magahern on 11/16/18. // Copyright © 2018 James Magahern. All rights reserved. // #import "MBIMHTTPConnection.h" #import "MBIMBridge.h" #import "MBIMBridgeOperation.h" @implementation MBIMHTTPConnection { NSMutableData *_bodyData; } - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path { if ([method isEqualToString:@"GET"] || [method isEqualToString:@"POST"]) { return YES; } return NO; } - (NSObject *)httpResponseForMethod:(NSString *)method URI:(NSString *)path { __block NSObject *response = nil; dispatch_semaphore_t sema = dispatch_semaphore_create(0); MBIMBridgeOperationCompletionBlock completion = ^(NSObject *incomingResponse) { response = incomingResponse; dispatch_semaphore_signal(sema); }; NSURL *url = [NSURL URLWithString:path]; NSString *endpointName = [url lastPathComponent]; Class operationClass = [MBIMBridgeOperation operationClassForEndpointName:endpointName]; if (operationClass != nil) { MBIMBridgeOperation *operation = [[operationClass alloc] initWithRequestURL:url completion:completion]; operation.requestBodyData = _bodyData; [[[MBIMBridge sharedInstance] operationQueue] addOperation:operation]; dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC))); } else { response = [[HTTPErrorResponse alloc] initWithErrorCode:404]; } return response; } - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path { if ([method isEqualToString:@"POST"]) { return YES; } return NO; } - (void)prepareForBodyWithSize:(UInt64)contentLength { _bodyData = [[NSMutableData alloc] initWithCapacity:contentLength]; } - (void)processBodyData:(NSData *)postDataChunk { [_bodyData appendData:postDataChunk]; } @end