How to use Foundation.NSDictionary class

Best Nimble code snippet using Foundation.NSDictionary

ObjcModelTranslatorTest.swift

Source:ObjcModelTranslatorTest.swift Github

copy

Full Screen

1import XCTest2import ReverseJsonCore3@testable import ReverseJsonObjc4class ObjcModelTranslatorTest: XCTestCase {5 6 func testSimpleString() {7 let type: FieldType = .text8 9 let modelCreator = ObjcModelCreator()10 let modelResult: String = modelCreator.translate(type, name: "SimpleText")11 XCTAssertEqual("", modelResult)12 }13 14 func testSimpleInt() {15 let type: FieldType = .number(.int)16 17 let modelCreator = ObjcModelCreator()18 let modelResult: String = modelCreator.translate(type, name: "SimpleNumber")19 XCTAssertEqual("", modelResult)20 }21 func testSimpleFloat() {22 let type: FieldType = .number(.float)23 24 let modelCreator = ObjcModelCreator()25 let modelResult: String = modelCreator.translate(type, name: "SimpleNumber")26 XCTAssertEqual("", modelResult)27 }28 29 func testSimpleDouble() {30 let type: FieldType = .number(.double)31 32 let modelCreator = ObjcModelCreator()33 let modelResult: String = modelCreator.translate(type, name: "SimpleNumber")34 XCTAssertEqual("", modelResult)35 }36 37 func testBoolDouble() {38 let type: FieldType = .number(.bool)39 40 let modelCreator = ObjcModelCreator()41 let modelResult: String = modelCreator.translate(type, name: "SimpleNumber")42 XCTAssertEqual("", modelResult)43 }44 45 func testEmptyObject() {46 let type: FieldType = .unnamedObject([])47 48 let modelCreator = ObjcModelCreator()49 let modelResult: String = modelCreator.translate(type, name: "TestObject")50 XCTAssertEqual(String(lines:51 "// TestObject.h",52 "#import <Foundation/Foundation.h>",53 "NS_ASSUME_NONNULL_BEGIN",54 "@interface TestObject : NSObject",55 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",56 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",57 "@end",58 "NS_ASSUME_NONNULL_END",59 "// TestObject.m",60 "#import \"TestObject.h\"",61 "@implementation TestObject",62 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",63 " self = [super init];",64 " if (self) {",65 " }",66 " return self;",67 "}",68 "- (instancetype)initWithJsonValue:(id)jsonValue {",69 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",70 " self = [self initWithJsonDictionary:jsonValue];",71 " } else {",72 " self = nil;",73 " }",74 " return self;",75 "}",76 "@end"77 ), modelResult)78 }79 80 func testNamedEmptyObject() {81 let type: FieldType = .object(name: "CustomObjectName", [])82 83 let modelCreator = ObjcModelCreator()84 let modelResult: String = modelCreator.translate(type, name: "TestObject")85 XCTAssertEqual(String(lines:86 "// CustomObjectName.h",87 "#import <Foundation/Foundation.h>",88 "NS_ASSUME_NONNULL_BEGIN",89 "@interface CustomObjectName : NSObject",90 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",91 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",92 "@end",93 "NS_ASSUME_NONNULL_END",94 "// CustomObjectName.m",95 "#import \"CustomObjectName.h\"",96 "@implementation CustomObjectName",97 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",98 " self = [super init];",99 " if (self) {",100 " }",101 " return self;",102 "}",103 "- (instancetype)initWithJsonValue:(id)jsonValue {",104 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",105 " self = [self initWithJsonDictionary:jsonValue];",106 " } else {",107 " self = nil;",108 " }",109 " return self;",110 "}",111 "@end"112 ), modelResult)113 }114 115 func testEmptyEnum() {116 let type: FieldType = .unnamedEnum([])117 118 let modelCreator = ObjcModelCreator()119 let modelResult: String = modelCreator.translate(type, name: "TestObject")120 XCTAssertEqual(String(lines:121 "// TestObject.h",122 "#import <Foundation/Foundation.h>",123 "NS_ASSUME_NONNULL_BEGIN",124 "@interface TestObject : NSObject",125 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",126 "@end",127 "NS_ASSUME_NONNULL_END",128 "// TestObject.m",129 "#import \"TestObject.h\"",130 "@implementation TestObject",131 "- (instancetype)initWithJsonValue:(id)jsonValue {",132 " self = [super init];",133 " if (self) {",134 " }",135 " return self;",136 "}",137 "@end"138 ), modelResult)139 }140 141 func testNamedEmptyEnum() {142 let type: FieldType = .enum(name: "CustomObject", [])143 144 let modelCreator = ObjcModelCreator()145 let modelResult: String = modelCreator.translate(type, name: "TestObject")146 XCTAssertEqual(String(lines:147 "// CustomObject.h",148 "#import <Foundation/Foundation.h>",149 "NS_ASSUME_NONNULL_BEGIN",150 "@interface CustomObject : NSObject",151 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",152 "@end",153 "NS_ASSUME_NONNULL_END",154 "// CustomObject.m",155 "#import \"CustomObject.h\"",156 "@implementation CustomObject",157 "- (instancetype)initWithJsonValue:(id)jsonValue {",158 " self = [super init];",159 " if (self) {",160 " }",161 " return self;",162 "}",163 "@end"164 ), modelResult)165 }166 167 func testTextList() {168 let type: FieldType = .list(.text)169 170 let modelCreator = ObjcModelCreator()171 let modelResult: String = modelCreator.translate(type, name: "TextList")172 XCTAssertEqual("", modelResult)173 }174 175 func testUnknownType() {176 let type: FieldType = .unnamedUnknown177 178 let modelCreator = ObjcModelCreator()179 let modelResult: String = modelCreator.translate(type, name: "MyTypeName")180 XCTAssertEqual("", modelResult)181 }182 183 func testListOfEmptyObject() {184 let modelCreator = ObjcModelCreator()185 let modelResult: String = modelCreator.translate(.list(.unnamedObject([])), name: "TestObjectList")186 XCTAssertEqual(String(lines:187 "// TestObjectListItem.h",188 "#import <Foundation/Foundation.h>",189 "NS_ASSUME_NONNULL_BEGIN",190 "@interface TestObjectListItem : NSObject",191 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",192 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",193 "@end",194 "NS_ASSUME_NONNULL_END",195 "// TestObjectListItem.m",196 "#import \"TestObjectListItem.h\"",197 "@implementation TestObjectListItem",198 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",199 " self = [super init];",200 " if (self) {",201 " }",202 " return self;",203 "}",204 "- (instancetype)initWithJsonValue:(id)jsonValue {",205 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",206 " self = [self initWithJsonDictionary:jsonValue];",207 " } else {",208 " self = nil;",209 " }",210 " return self;",211 "}",212 "@end"213 ), modelResult)214 }215 func testObjectWithSingleTextField() {216 let type: FieldType = .unnamedObject([.init(name: "text", type: .text)])217 218 let modelCreator = ObjcModelCreator()219 let modelResult: String = modelCreator.translate(type, name: "TestObject")220 XCTAssertEqual(String(lines:221 "// TestObject.h",222 "#import <Foundation/Foundation.h>",223 "NS_ASSUME_NONNULL_BEGIN",224 "@interface TestObject : NSObject",225 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",226 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",227 "@property (nonatomic, copy, readonly) NSString *text;",228 "@end",229 "NS_ASSUME_NONNULL_END",230 "// TestObject.m",231 "#import \"TestObject.h\"",232 "@implementation TestObject",233 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",234 " self = [super init];",235 " if (self) {",236 " _text = [dict[@\"text\"] isKindOfClass:[NSString class]] ? dict[@\"text\"] : @\"\";",237 " }",238 " return self;",239 "}",240 "- (instancetype)initWithJsonValue:(id)jsonValue {",241 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",242 " self = [self initWithJsonDictionary:jsonValue];",243 " } else {",244 " self = nil;",245 " }",246 " return self;",247 "}",248 "@end"249 ), modelResult)250 }251 252 func testObjectWithSingleTextFieldAndReverseMapper() {253 let type: FieldType = .unnamedObject([.init(name: "text", type: .text)])254 255 var modelCreator = ObjcModelCreator()256 modelCreator.createToJson = true257 let modelResult: String = modelCreator.translate(type, name: "TestObject")258 XCTAssertEqual(String(lines:259 "// TestObject.h",260 "#import <Foundation/Foundation.h>",261 "NS_ASSUME_NONNULL_BEGIN",262 "@interface TestObject : NSObject",263 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",264 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",265 "- (NSDictionary<NSString *, id<NSObject>> *)toJson;",266 "@property (nonatomic, copy, readonly) NSString *text;",267 "@end",268 "NS_ASSUME_NONNULL_END",269 "// TestObject.m",270 "#import \"TestObject.h\"",271 "@implementation TestObject",272 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",273 " self = [super init];",274 " if (self) {",275 " _text = [dict[@\"text\"] isKindOfClass:[NSString class]] ? dict[@\"text\"] : @\"\";",276 " }",277 " return self;",278 "}",279 "- (instancetype)initWithJsonValue:(id)jsonValue {",280 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",281 " self = [self initWithJsonDictionary:jsonValue];",282 " } else {",283 " self = nil;",284 " }",285 " return self;",286 "}",287 "- (NSDictionary<NSString *, id<NSObject>> *)toJson {",288 " NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithCapacity:1];",289 " ret[@\"text\"] = _text;",290 " return [ret copy];",291 "}",292 "@end"293 ), modelResult)294 }295 296 func testObjectWithSingleReservedTextField() {297 let type: FieldType = .unnamedObject([.init(name: "signed", type: .text)])298 299 let modelCreator = ObjcModelCreator()300 let modelResult: String = modelCreator.translate(type, name: "TestObject")301 XCTAssertEqual(String(lines:302 "// TestObject.h",303 "#import <Foundation/Foundation.h>",304 "NS_ASSUME_NONNULL_BEGIN",305 "@interface TestObject : NSObject",306 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",307 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",308 "@property (nonatomic, copy, readonly) NSString *$signed;",309 "@end",310 "NS_ASSUME_NONNULL_END",311 "// TestObject.m",312 "#import \"TestObject.h\"",313 "@implementation TestObject",314 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",315 " self = [super init];",316 " if (self) {",317 " _$signed = [dict[@\"signed\"] isKindOfClass:[NSString class]] ? dict[@\"signed\"] : @\"\";",318 " }",319 " return self;",320 "}",321 "- (instancetype)initWithJsonValue:(id)jsonValue {",322 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",323 " self = [self initWithJsonDictionary:jsonValue];",324 " } else {",325 " self = nil;",326 " }",327 " return self;",328 "}",329 "@end"330 ), modelResult)331 }332 333 func testObjectWithFieldContainingListOfText() {334 let type: FieldType = .unnamedObject([.init(name: "texts", type: .list(.text))])335 336 let modelCreator = ObjcModelCreator()337 let modelResult: String = modelCreator.translate(type, name: "TestObject")338 XCTAssertEqual(String(lines:339 "// TestObject.h",340 "#import <Foundation/Foundation.h>",341 "NS_ASSUME_NONNULL_BEGIN",342 "@interface TestObject : NSObject",343 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",344 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",345 "@property (nonatomic, strong, readonly) NSArray<NSString *> *texts;",346 "@end",347 "NS_ASSUME_NONNULL_END",348 "// TestObject.m",349 "#import \"TestObject.h\"",350 "@implementation TestObject",351 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",352 " self = [super init];",353 " if (self) {",354 " _texts = ({",355 " id value = dict[@\"texts\"];",356 " NSMutableArray<NSString *> *values = nil;",357 " if ([value isKindOfClass:[NSArray class]]) {",358 " NSArray *array = value;",359 " values = [NSMutableArray arrayWithCapacity:array.count];",360 " for (id item in array) {",361 " NSString *parsedItem = [item isKindOfClass:[NSString class]] ? item : @\"\";",362 " [values addObject:parsedItem ?: (id)[NSNull null]];",363 " }",364 " }",365 " [values copy] ?: @[];",366 " });",367 " }",368 " return self;",369 "}",370 "- (instancetype)initWithJsonValue:(id)jsonValue {",371 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",372 " self = [self initWithJsonDictionary:jsonValue];",373 " } else {",374 " self = nil;",375 " }",376 " return self;",377 "}",378 "@end"379 ), modelResult)380 }381 382 func testObjectWithFieldContainingListOfTextWithReverseMapper() {383 let type: FieldType = .unnamedObject([.init(name: "texts", type: .list(.text))])384 385 var modelCreator = ObjcModelCreator()386 modelCreator.createToJson = true387 let modelResult: String = modelCreator.translate(type, name: "TestObject")388 XCTAssertEqual(String(lines:389 "// TestObject.h",390 "#import <Foundation/Foundation.h>",391 "NS_ASSUME_NONNULL_BEGIN",392 "@interface TestObject : NSObject",393 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",394 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",395 "- (NSDictionary<NSString *, id<NSObject>> *)toJson;",396 "@property (nonatomic, strong, readonly) NSArray<NSString *> *texts;",397 "@end",398 "NS_ASSUME_NONNULL_END",399 "// TestObject.m",400 "#import \"TestObject.h\"",401 "@implementation TestObject",402 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",403 " self = [super init];",404 " if (self) {",405 " _texts = ({",406 " id value = dict[@\"texts\"];",407 " NSMutableArray<NSString *> *values = nil;",408 " if ([value isKindOfClass:[NSArray class]]) {",409 " NSArray *array = value;",410 " values = [NSMutableArray arrayWithCapacity:array.count];",411 " for (id item in array) {",412 " NSString *parsedItem = [item isKindOfClass:[NSString class]] ? item : @\"\";",413 " [values addObject:parsedItem ?: (id)[NSNull null]];",414 " }",415 " }",416 " [values copy] ?: @[];",417 " });",418 " }",419 " return self;",420 "}",421 "- (instancetype)initWithJsonValue:(id)jsonValue {",422 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",423 " self = [self initWithJsonDictionary:jsonValue];",424 " } else {",425 " self = nil;",426 " }",427 " return self;",428 "}",429 "- (NSDictionary<NSString *, id<NSObject>> *)toJson {",430 " NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithCapacity:1];",431 " ret[@\"texts\"] = ({",432 " NSMutableArray<id<NSObject>> *values = nil;",433 " NSArray *array = _texts;",434 " if (array) {",435 " values = [NSMutableArray arrayWithCapacity:array.count];",436 " for (id item in array) {",437 " if (item == [NSNull null]) {",438 " [values addObject:item];",439 " } else {",440 " id json = item;",441 " [values addObject:json ?: (id)[NSNull null]];",442 " }",443 " }",444 " }",445 " [values copy] ?: @[];",446 " });",447 " return [ret copy];",448 "}",449 "@end"450 ), modelResult)451 }452 453 func testObjectWithFieldContainingOptionalListOfText() {454 let type: FieldType = .unnamedObject([.init(name: "texts", type: .optional(.list(.text)))])455 456 let modelCreator = ObjcModelCreator()457 let modelResult: String = modelCreator.translate(type, name: "TestObject")458 XCTAssertEqual(String(lines:459 "// TestObject.h",460 "#import <Foundation/Foundation.h>",461 "NS_ASSUME_NONNULL_BEGIN",462 "@interface TestObject : NSObject",463 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",464 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",465 "@property (nonatomic, strong, readonly, nullable) NSArray<NSString *> *texts;",466 "@end",467 "NS_ASSUME_NONNULL_END",468 "// TestObject.m",469 "#import \"TestObject.h\"",470 "@implementation TestObject",471 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",472 " self = [super init];",473 " if (self) {",474 " _texts = ({",475 " id value = dict[@\"texts\"];",476 " NSMutableArray<NSString *> *values = nil;",477 " if ([value isKindOfClass:[NSArray class]]) {",478 " NSArray *array = value;",479 " values = [NSMutableArray arrayWithCapacity:array.count];",480 " for (id item in array) {",481 " NSString *parsedItem = [item isKindOfClass:[NSString class]] ? item : @\"\";",482 " [values addObject:parsedItem ?: (id)[NSNull null]];",483 " }",484 " }",485 " [values copy];",486 " });",487 " }",488 " return self;",489 "}",490 "- (instancetype)initWithJsonValue:(id)jsonValue {",491 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",492 " self = [self initWithJsonDictionary:jsonValue];",493 " } else {",494 " self = nil;",495 " }",496 " return self;",497 "}",498 "@end"499 ), modelResult)500 }501 func testObjectWithDifferentFields() {502 let modelCreator = ObjcModelCreator()503 let modelResult: String = modelCreator.translate(.unnamedObject([504 .init(name: "listOfListsOfText", type: .list(.list(.text))),505 .init(name: "numbers", type: .list(.number(.int))),506 .init(name: "int", type: .number(.int)),507 .init(name: "optionalText", type: .optional(.text))508 ]), name: "TestObject")509 XCTAssertEqual(String(lines:510 "// TestObject.h",511 "#import <Foundation/Foundation.h>",512 "NS_ASSUME_NONNULL_BEGIN",513 "@interface TestObject : NSObject",514 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",515 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",516 "@property (nonatomic, strong, readonly) NSArray<NSArray<NSString *> *> *listOfListsOfText;",517 "@property (nonatomic, strong, readonly) NSArray<NSNumber/*NSInteger*/ *> *numbers;",518 "@property (nonatomic, assign, readonly) NSInteger $int;",519 "@property (nonatomic, strong, readonly, nullable) NSString *optionalText;",520 "@end",521 "NS_ASSUME_NONNULL_END",522 "// TestObject.m",523 "#import \"TestObject.h\"",524 "@implementation TestObject",525 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",526 " self = [super init];",527 " if (self) {",528 " _listOfListsOfText = ({",529 " id value = dict[@\"listOfListsOfText\"];",530 " NSMutableArray<NSArray<NSString *> *> *values = nil;",531 " if ([value isKindOfClass:[NSArray class]]) {",532 " NSArray *array = value;",533 " values = [NSMutableArray arrayWithCapacity:array.count];",534 " for (id item in array) {",535 " NSArray<NSString *> *parsedItem = ({",536 " id value = item;",537 " NSMutableArray<NSString *> *values = nil;",538 " if ([value isKindOfClass:[NSArray class]]) {",539 " NSArray *array = value;",540 " values = [NSMutableArray arrayWithCapacity:array.count];",541 " for (id item in array) {",542 " NSString *parsedItem = [item isKindOfClass:[NSString class]] ? item : @\"\";",543 " [values addObject:parsedItem ?: (id)[NSNull null]];",544 " }",545 " }",546 " [values copy] ?: @[];",547 " });",548 " [values addObject:parsedItem ?: (id)[NSNull null]];",549 " }",550 " }",551 " [values copy] ?: @[];",552 " });",553 " _numbers = ({",554 " id value = dict[@\"numbers\"];",555 " NSMutableArray<NSNumber/*NSInteger*/ *> *values = nil;",556 " if ([value isKindOfClass:[NSArray class]]) {",557 " NSArray *array = value;",558 " values = [NSMutableArray arrayWithCapacity:array.count];",559 " for (id item in array) {",560 " NSNumber/*NSInteger*/ *parsedItem = [item isKindOfClass:[NSNumber class]] ? item : nil;",561 " [values addObject:parsedItem ?: (id)[NSNull null]];",562 " }",563 " }",564 " [values copy] ?: @[];",565 " });",566 " _$int = [dict[@\"int\"] isKindOfClass:[NSNumber class]] ? [dict[@\"int\"] integerValue] : 0;",567 " _optionalText = [dict[@\"optionalText\"] isKindOfClass:[NSString class]] ? dict[@\"optionalText\"] : nil;",568 " }",569 " return self;",570 "}",571 "- (instancetype)initWithJsonValue:(id)jsonValue {",572 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",573 " self = [self initWithJsonDictionary:jsonValue];",574 " } else {",575 " self = nil;",576 " }",577 " return self;",578 "}",579 "@end"580 ), modelResult)581 }582 583 func testObjectWithOneFieldWithSubDeclaration() {584 let modelCreator = ObjcModelCreator()585 let modelResult: String = modelCreator.translate(.unnamedObject([586 .init(name: "subObject", type: .unnamedObject([]))587 ]), name: "TestObject")588 XCTAssertEqual(String(lines:589 "// TestObject.h",590 "#import <Foundation/Foundation.h>",591 "@class TestObjectSubObject;",592 "NS_ASSUME_NONNULL_BEGIN",593 "@interface TestObject : NSObject",594 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",595 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",596 "@property (nonatomic, strong, readonly) TestObjectSubObject *subObject;",597 "@end",598 "NS_ASSUME_NONNULL_END",599 "// TestObjectSubObject.h",600 "#import <Foundation/Foundation.h>",601 "NS_ASSUME_NONNULL_BEGIN",602 "@interface TestObjectSubObject : NSObject",603 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",604 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",605 "@end",606 "NS_ASSUME_NONNULL_END",607 "// TestObject.m",608 "#import \"TestObject.h\"",609 "#import \"TestObjectSubObject.h\"",610 "@implementation TestObject",611 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",612 " self = [super init];",613 " if (self) {",614 " _subObject = ([[TestObjectSubObject alloc] initWithJsonValue:dict[@\"subObject\"]] ?: [[TestObjectSubObject alloc] initWithJsonDictionary:@{}]);",615 " }",616 " return self;",617 "}",618 "- (instancetype)initWithJsonValue:(id)jsonValue {",619 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",620 " self = [self initWithJsonDictionary:jsonValue];",621 " } else {",622 " self = nil;",623 " }",624 " return self;",625 "}",626 "@end",627 "// TestObjectSubObject.m",628 "#import \"TestObjectSubObject.h\"",629 "@implementation TestObjectSubObject",630 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",631 " self = [super init];",632 " if (self) {",633 " }",634 " return self;",635 "}",636 "- (instancetype)initWithJsonValue:(id)jsonValue {",637 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",638 " self = [self initWithJsonDictionary:jsonValue];",639 " } else {",640 " self = nil;",641 " }",642 " return self;",643 "}",644 "@end"645 ), modelResult)646 }647 648 func testEnumWithOneCase() {649 let type: FieldType = .unnamedEnum([.text])650 651 let modelCreator = ObjcModelCreator()652 let modelResult: String = modelCreator.translate(type, name: "TestObject")653 XCTAssertEqual(String(lines:654 "// TestObject.h",655 "#import <Foundation/Foundation.h>",656 "NS_ASSUME_NONNULL_BEGIN",657 "@interface TestObject : NSObject",658 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",659 "@property (nonatomic, copy, readonly) NSString *text;",660 "@end",661 "NS_ASSUME_NONNULL_END",662 "// TestObject.m",663 "#import \"TestObject.h\"",664 "@implementation TestObject",665 "- (instancetype)initWithJsonValue:(id)jsonValue {",666 " self = [super init];",667 " if (self) {",668 " _text = [jsonValue isKindOfClass:[NSString class]] ? jsonValue : @\"\";",669 " }",670 " return self;",671 "}",672 "@end"673 ), modelResult)674 }675 676 func testEnumWithOneCaseAndReverseMapping() {677 let type: FieldType = .unnamedEnum([.text])678 679 var modelCreator = ObjcModelCreator()680 modelCreator.createToJson = true681 let modelResult: String = modelCreator.translate(type, name: "TestObject")682 XCTAssertEqual(String(lines:683 "// TestObject.h",684 "#import <Foundation/Foundation.h>",685 "NS_ASSUME_NONNULL_BEGIN",686 "@interface TestObject : NSObject",687 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",688 "- (id<NSObject>)toJson;",689 "@property (nonatomic, copy, readonly) NSString *text;",690 "@end",691 "NS_ASSUME_NONNULL_END",692 "// TestObject.m",693 "#import \"TestObject.h\"",694 "@implementation TestObject",695 "- (instancetype)initWithJsonValue:(id)jsonValue {",696 " self = [super init];",697 " if (self) {",698 " _text = [jsonValue isKindOfClass:[NSString class]] ? jsonValue : @\"\";",699 " }",700 " return self;",701 "}",702 "- (id<NSObject>)toJson {",703 " if (_text) {",704 " return _text;",705 " }",706 " return nil;",707 "}",708 "@end"709 ), modelResult)710 }711 712 func testEnumWithTwoCases() {713 let type: FieldType = .unnamedEnum([714 .optional(.unnamedObject([])),715 .number(.int)716 ])717 718 let modelCreator = ObjcModelCreator()719 let modelResult: String = modelCreator.translate(type, name: "TestObject")720 XCTAssertEqual(String(lines:721 "// TestObject.h",722 "#import <Foundation/Foundation.h>",723 "@class TestObjectObject;",724 "NS_ASSUME_NONNULL_BEGIN",725 "@interface TestObject : NSObject",726 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",727 "@property (nonatomic, copy, readonly, nullable) NSNumber/*NSInteger*/ *number;",728 "@property (nonatomic, strong, readonly, nullable) TestObjectObject *object;",729 "@end",730 "NS_ASSUME_NONNULL_END",731 "// TestObjectObject.h",732 "#import <Foundation/Foundation.h>",733 "NS_ASSUME_NONNULL_BEGIN",734 "@interface TestObjectObject : NSObject",735 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",736 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",737 "@end",738 "NS_ASSUME_NONNULL_END",739 "// TestObject.m",740 "#import \"TestObject.h\"",741 "#import \"TestObjectObject.h\"",742 "@implementation TestObject",743 "- (instancetype)initWithJsonValue:(id)jsonValue {",744 " self = [super init];",745 " if (self) {",746 " _number = [jsonValue isKindOfClass:[NSNumber class]] ? jsonValue : nil;",747 " _object = [[TestObjectObject alloc] initWithJsonValue:jsonValue];",748 " }",749 " return self;",750 "}",751 "@end",752 "// TestObjectObject.m",753 "#import \"TestObjectObject.h\"",754 "@implementation TestObjectObject",755 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",756 " self = [super init];",757 " if (self) {",758 " }",759 " return self;",760 "}",761 "- (instancetype)initWithJsonValue:(id)jsonValue {",762 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",763 " self = [self initWithJsonDictionary:jsonValue];",764 " } else {",765 " self = nil;",766 " }",767 " return self;",768 "}",769 "@end"770 ), modelResult)771 }772 func testEnumWithTwoCasesAndReverseMapping() {773 let type: FieldType = .unnamedEnum([774 .optional(.unnamedObject([])),775 .number(.int)776 ])777 778 var modelCreator = ObjcModelCreator()779 modelCreator.createToJson = true780 let modelResult: String = modelCreator.translate(type, name: "TestObject")781 XCTAssertEqual(String(lines:782 "// TestObject.h",783 "#import <Foundation/Foundation.h>",784 "@class TestObjectObject;",785 "NS_ASSUME_NONNULL_BEGIN",786 "@interface TestObject : NSObject",787 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",788 "- (id<NSObject>)toJson;",789 "@property (nonatomic, copy, readonly, nullable) NSNumber/*NSInteger*/ *number;",790 "@property (nonatomic, strong, readonly, nullable) TestObjectObject *object;",791 "@end",792 "NS_ASSUME_NONNULL_END",793 "// TestObjectObject.h",794 "#import <Foundation/Foundation.h>",795 "NS_ASSUME_NONNULL_BEGIN",796 "@interface TestObjectObject : NSObject",797 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",798 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",799 "- (NSDictionary<NSString *, id<NSObject>> *)toJson;",800 "@end",801 "NS_ASSUME_NONNULL_END",802 "// TestObject.m",803 "#import \"TestObject.h\"",804 "#import \"TestObjectObject.h\"",805 "@implementation TestObject",806 "- (instancetype)initWithJsonValue:(id)jsonValue {",807 " self = [super init];",808 " if (self) {",809 " _number = [jsonValue isKindOfClass:[NSNumber class]] ? jsonValue : nil;",810 " _object = [[TestObjectObject alloc] initWithJsonValue:jsonValue];",811 " }",812 " return self;",813 "}",814 "- (id<NSObject>)toJson {",815 " if (_number) {",816 " return _number;",817 " } else if (_object) {",818 " return [_object toJson];",819 " }",820 " return nil;",821 "}",822 "@end",823 "// TestObjectObject.m",824 "#import \"TestObjectObject.h\"",825 "@implementation TestObjectObject",826 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",827 " self = [super init];",828 " if (self) {",829 " }",830 " return self;",831 "}",832 "- (instancetype)initWithJsonValue:(id)jsonValue {",833 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",834 " self = [self initWithJsonDictionary:jsonValue];",835 " } else {",836 " self = nil;",837 " }",838 " return self;",839 "}",840 "- (NSDictionary<NSString *, id<NSObject>> *)toJson {",841 " NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithCapacity:0];",842 " return [ret copy];",843 "}",844 "@end"845 ), modelResult)846 }847 848 func testNamedEnumWithTwoCasesAndReverseMapping() {849 let type: FieldType = .enum(name: "CustomEnumName", [850 .optional(.object(name: "CustomObjectName", [])),851 .number(.int)852 ])853 854 var modelCreator = ObjcModelCreator()855 modelCreator.createToJson = true856 let modelResult: String = modelCreator.translate(type, name: "TestObject")857 XCTAssertEqual(String(lines:858 "// CustomEnumName.h",859 "#import <Foundation/Foundation.h>",860 "@class CustomObjectName;",861 "NS_ASSUME_NONNULL_BEGIN",862 "@interface CustomEnumName : NSObject",863 "- (instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",864 "- (id<NSObject>)toJson;",865 "@property (nonatomic, strong, readonly, nullable) CustomObjectName *customObjectName;",866 "@property (nonatomic, copy, readonly, nullable) NSNumber/*NSInteger*/ *number;",867 "@end",868 "NS_ASSUME_NONNULL_END",869 "// CustomObjectName.h",870 "#import <Foundation/Foundation.h>",871 "NS_ASSUME_NONNULL_BEGIN",872 "@interface CustomObjectName : NSObject",873 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",874 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",875 "- (NSDictionary<NSString *, id<NSObject>> *)toJson;",876 "@end",877 "NS_ASSUME_NONNULL_END",878 "// CustomEnumName.m",879 "#import \"CustomEnumName.h\"",880 "#import \"CustomObjectName.h\"",881 "@implementation CustomEnumName",882 "- (instancetype)initWithJsonValue:(id)jsonValue {",883 " self = [super init];",884 " if (self) {",885 " _customObjectName = [[CustomObjectName alloc] initWithJsonValue:jsonValue];",886 " _number = [jsonValue isKindOfClass:[NSNumber class]] ? jsonValue : nil;",887 " }",888 " return self;",889 "}",890 "- (id<NSObject>)toJson {",891 " if (_customObjectName) {",892 " return [_customObjectName toJson];",893 " } else if (_number) {",894 " return _number;",895 " }",896 " return nil;",897 "}",898 "@end",899 "// CustomObjectName.m",900 "#import \"CustomObjectName.h\"",901 "@implementation CustomObjectName",902 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",903 " self = [super init];",904 " if (self) {",905 " }",906 " return self;",907 "}",908 "- (instancetype)initWithJsonValue:(id)jsonValue {",909 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",910 " self = [self initWithJsonDictionary:jsonValue];",911 " } else {",912 " self = nil;",913 " }",914 " return self;",915 "}",916 "- (NSDictionary<NSString *, id<NSObject>> *)toJson {",917 " NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithCapacity:0];",918 " return [ret copy];",919 "}",920 "@end"921 ), modelResult)922 }923 func testAtomicFieldsFlag() {924 let type: FieldType = .unnamedObject([.init(name: "text", type: .text)])925 926 var modelCreator = ObjcModelCreator()927 modelCreator.atomic = true928 let modelResult: String = modelCreator.translate(type, name: "TestObject")929 let expected = String(lines:930 "// TestObject.h",931 "#import <Foundation/Foundation.h>",932 "NS_ASSUME_NONNULL_BEGIN",933 "@interface TestObject : NSObject",934 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",935 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",936 "@property (atomic, copy, readonly) NSString *text;",937 "@end",938 "NS_ASSUME_NONNULL_END",939 "// TestObject.m",940 "#import \"TestObject.h\"",941 "@implementation TestObject",942 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",943 " self = [super init];",944 " if (self) {",945 " _text = [dict[@\"text\"] isKindOfClass:[NSString class]] ? dict[@\"text\"] : @\"\";",946 " }",947 " return self;",948 "}",949 "- (instancetype)initWithJsonValue:(id)jsonValue {",950 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",951 " self = [self initWithJsonDictionary:jsonValue];",952 " } else {",953 " self = nil;",954 " }",955 " return self;",956 "}",957 "@end"958 )959 XCTAssertEqual(expected, modelResult)960 }961 962 func testMutableFieldsFlag() {963 let type: FieldType = .unnamedObject([.init(name: "text", type: .text)])964 965 var modelCreator = ObjcModelCreator()966 modelCreator.readonly = false967 let modelResult: String = modelCreator.translate(type, name: "TestObject")968 let expected = String(lines:969 "// TestObject.h",970 "#import <Foundation/Foundation.h>",971 "NS_ASSUME_NONNULL_BEGIN",972 "@interface TestObject : NSObject",973 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",974 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",975 "@property (nonatomic, copy) NSString *text;",976 "@end",977 "NS_ASSUME_NONNULL_END",978 "// TestObject.m",979 "#import \"TestObject.h\"",980 "@implementation TestObject",981 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",982 " self = [super init];",983 " if (self) {",984 " _text = [dict[@\"text\"] isKindOfClass:[NSString class]] ? dict[@\"text\"] : @\"\";",985 " }",986 " return self;",987 "}",988 "- (instancetype)initWithJsonValue:(id)jsonValue {",989 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",990 " self = [self initWithJsonDictionary:jsonValue];",991 " } else {",992 " self = nil;",993 " }",994 " return self;",995 "}",996 "@end"997 )998 XCTAssertEqual(expected, modelResult)999 }1000 1001 1002 func testPrefixOption() {1003 let type: FieldType = .unnamedObject([.init(name: "text", type: .text)])1004 1005 var modelCreator = ObjcModelCreator()1006 modelCreator.typePrefix = "ABC"1007 let modelResult: String = modelCreator.translate(type, name: "TestObject")1008 let expected = [1009 "// ABCTestObject.h",1010 "#import <Foundation/Foundation.h>",1011 "NS_ASSUME_NONNULL_BEGIN",1012 "@interface ABCTestObject : NSObject",1013 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id<NSObject>> *)dictionary;",1014 "- (nullable instancetype)initWithJsonValue:(nullable id<NSObject>)jsonValue;",1015 "@property (nonatomic, copy, readonly) NSString *text;",1016 "@end",1017 "NS_ASSUME_NONNULL_END",1018 "// ABCTestObject.m",1019 "#import \"ABCTestObject.h\"",1020 "@implementation ABCTestObject",1021 "- (instancetype)initWithJsonDictionary:(NSDictionary<NSString *, id> *)dict {",1022 " self = [super init];",1023 " if (self) {",1024 " _text = [dict[@\"text\"] isKindOfClass:[NSString class]] ? dict[@\"text\"] : @\"\";",1025 " }",1026 " return self;",1027 "}",1028 "- (instancetype)initWithJsonValue:(id)jsonValue {",1029 " if ([jsonValue isKindOfClass:[NSDictionary class]]) {",1030 " self = [self initWithJsonDictionary:jsonValue];",1031 " } else {",1032 " self = nil;",1033 " }",1034 " return self;",1035 "}",1036 "@end"1037 ].joined(separator: "\n")1038 XCTAssertEqual(expected, modelResult)1039 }1040 1041}...

Full Screen

Full Screen

JsapiRest.swift

Source:JsapiRest.swift Github

copy

Full Screen

1//2// JsapiRest.swift3// JsapiApi4//5// Created by youssef on 3/12/15.6// Copyright (c) 2015 Knetik. All rights reserved.7//8import Foundation9fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {10 switch (lhs, rhs) {11 case let (l?, r?):12 return l < r13 case (nil, _?):14 return true15 default:16 return false17 }18}19fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {20 switch (lhs, rhs) {21 case let (l?, r?):22 return l <= r23 default:24 return !(rhs < lhs)25 }26}27class JsapiRest :NSObject,URLSessionDelegate28{29 30 private static var __once: () = {31 Statics.instance=JsapiRest()32 33 }()34 35 fileprivate var requests:Dictionary<String,NSMutableURLRequest> = Dictionary<String,NSMutableURLRequest>()36 struct Statics37 {38 static var instance:JsapiRest?39 static var token:Int=040 41 }42 43 class var sharedInstance:JsapiRest44 {45 46 _ = JsapiRest.__once47 return Statics.instance!48 }49 50 //51 /**52 postRequet53 @param functionURL : function URL Example http://localhost:8080/jsapi/oauth/token54 @param postParams : post string55 @param isJson should sent true in case of json request56 @param callback block called once you got the response57 */58 func postrequest(_ functionURL:String,postParams:String,isJson:Bool,callback:@escaping (NSDictionary,Bool)->Void)59 {60 61 let request = NSMutableURLRequest(url: URL(string: functionURL)!)62 63 request.httpMethod = "POST"64 let postString = postParams65 request.httpBody = postString.data(using: String.Encoding.utf8)66 if(isJson)67 {68 request.setValue("application/json", forHTTPHeaderField: "Content-Type")69 request.setValue("application/json", forHTTPHeaderField: "Accept")70 71 72 if(!JsapiAPi.sharedInstance.getJsapiOriginalToken().isEmpty &&73 JsapiAPi.sharedInstance.getJsapiToken() != JSAPIConstant.TOKENBREAR74 && !functionURL.contains("google")75 )76 {77 request.setValue(JsapiAPi.sharedInstance.getJsapiToken(),forHTTPHeaderField:"Authorization")78 }79 }else{80 81 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")82 }83 self.requests[functionURL] = request84 85 let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)86 87 88 let task = session.dataTask(with: request as URLRequest, completionHandler: {89 data, response, error in90 if error != nil {91 92 var res = NSMutableDictionary();93 94 res.setValue(JSAPIConstant.CONNECTION_ERROR, forKey: "message")95 96 callback(res,false)97 return98 }99 //self.requests.removeValueForKey(request.URL!.absoluteString)100 101 let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)102 103 let httpResponse = response as! HTTPURLResponse104 105 106 if(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 && (responseString as! String) .isEmpty)107 {108 callback(NSDictionary(),true)109 110 return111 }112 113 //Redirection114 115 116 if(responseString == "")117 {118 callback(NSDictionary(),true)119 120 return;121 }122 let jsonResult2: AnyObject! = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers ) as AnyObject!123 124 if(jsonResult2 == nil ){125 callback(NSDictionary(),false)126 127 return128 }129 130 131 let jsonResult : NSDictionary = (jsonResult2 as?NSDictionary)!;132 133 134 if(httpResponse.statusCode == 301 || httpResponse.statusCode == 307){135 136 self.postrequest(httpResponse.url!.absoluteString , postParams: postParams, isJson: isJson, callback: callback)137 }138 139 140 if(jsonResult["error"] != nil && isJson)141 {142 if(jsonResult ["error"] as?String == "invalid_token") {143 144 JsapiAPi.sharedInstance.sessionExpired()145 146 callback(jsonResult,false)147 }148 149 if jsonResult["error"] is Dictionary<String,Bool>{150 let errorObject = jsonResult["error"] as! Dictionary<String,Bool>151 152 let isSuccess=errorObject["success"]153 callback(jsonResult,isSuccess!)154 155 }else156 {157 158 let isSuccess = false159 if let _ = jsonResult["error"] as? String {160 161 let errorObject = jsonResult["error"] as! String162 163 let error_description = jsonResult["error_description"] as! String164 var dictionary = Dictionary<String ,String>()165 dictionary.updateValue(errorObject,forKey: "error")166 dictionary.updateValue(error_description,forKey: "error_description")167 }168 callback(jsonResult , isSuccess)169 }170 171 }else172 if(jsonResult["error"] != nil || httpResponse.statusCode >= 400)173 {174 callback(jsonResult,false)175 176 }else177 {178 callback(jsonResult,true)179 }180 }) 181 task.resume()182 }183 184 185 //186 /**187 getRequet188 @param functionURL : function URL Example http://localhost:8080/jsapi/services/latest/carts/e9486b32-674189 @param callback block called once you got the response190 */191 func getRequest(_ functionURL:String,postParams:String,callback:@escaping (NSDictionary,Bool)->Void)192 {193 var endpoint:String = functionURL + postParams194 endpoint = endpoint.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!195 196 let request = NSMutableURLRequest(url: URL(string: endpoint )!)197 request.httpMethod = "GET"198 request.setValue("application/json", forHTTPHeaderField: "Content-Type")199 request.setValue("application/json", forHTTPHeaderField: "Accept")200 201 202 if(!JsapiAPi.sharedInstance.getJsapiToken().isEmpty&&JsapiAPi.sharedInstance.getJsapiToken() != JSAPIConstant.TOKENBREAR){203 204 request.setValue(JsapiAPi.sharedInstance.getJsapiToken(),forHTTPHeaderField:"Authorization")205 206 }207 self.requests[functionURL] = request208 209 let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)210 211 let task = session.dataTask(with: request as URLRequest, completionHandler: {212 data, response, error in213 if error != nil {214 215 let res = NSMutableDictionary();216 217 res.setValue(JSAPIConstant.CONNECTION_ERROR, forKey: "message")218 callback(res,false)219 return220 }221 222 223 let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)224 let httpResponse = response as! HTTPURLResponse225 if(httpResponse.statusCode == 301 || httpResponse.statusCode == 307 ){226 self.getRequest(httpResponse.url!.absoluteString , postParams: postParams,callback: callback)227 return;228 }229 if(data == nil || data?.count <= 0 ){230 231 callback(NSDictionary(),false)232 return;233 }234 235 let jsonResult2: AnyObject! = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject!236 if(jsonResult2 == nil)237 {238 callback(NSDictionary(),false)239 return;240 }241 var jsonResult:NSDictionary = NSDictionary();242 243 if jsonResult2 is Array<Any> {244 245 jsonResult = ["result":jsonResult2]246 247 callback(jsonResult as! NSDictionary,false)248 249 }else{250 251 jsonResult = (jsonResult2 as? NSDictionary)!252 253 }254 255 256 257 if(jsonResult["error"] != nil || httpResponse.statusCode >= 400)258 {259 if(jsonResult ["error"] as?String == "invalid_token") {260 261 JsapiAPi.sharedInstance.sessionExpired()262 263 callback(jsonResult,false)264 265 }else{266 267 if ((jsonResult["error"] as? NSDictionary) != nil) {268 269 let errorObject = jsonResult["error"] as! Dictionary<String,Bool>270 271 let isSuccess=errorObject["success"]272 callback(jsonResult,isSuccess!)273 }else{274 275 callback(jsonResult,false)276 277 }278 }279 }else280 {281 callback(jsonResult,true)282 }283 }) 284 task.resume()285 }286 287 288 289 //290 /**291 DELETERequet292 @param functionURL : function URL Example293 @param callback block called once you got the response294 */295 func deleteRequest(_ functionURL:String,deleteParams:String,callback:@escaping (NSDictionary,Bool)->Void)296 {297 let request = NSMutableURLRequest(url: URL(string: functionURL)!)298 request.httpMethod = "DELETE"299 request.setValue("application/json", forHTTPHeaderField: "Content-Type")300 request.setValue("application/json", forHTTPHeaderField: "Accept")301 302 303 if(!JsapiAPi.sharedInstance.getJsapiToken().isEmpty&&JsapiAPi.sharedInstance.getJsapiToken() != JSAPIConstant.TOKENBREAR){304 request.setValue(JsapiAPi.sharedInstance.getJsapiToken(),forHTTPHeaderField:"Authorization")305 306 }307 308 self.requests[functionURL] = request309 310 let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)311 312 let task = session.dataTask(with: request as URLRequest, completionHandler: {313 data, response, error in314 315 316 if error != nil {317 318 var res = NSMutableDictionary();319 320 res.setValue(JSAPIConstant.CONNECTION_ERROR, forKey: "message")321 callback(res,false)322 return323 }324 325 let httpResponse = response as! HTTPURLResponse326 327 // self.requests.removeValueForKey(request.URL!.absoluteString)328 329 let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)330 331 if(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 && (responseString as! String) .isEmpty)332 {333 callback(NSDictionary(),true)334 335 return336 }337 338 let jsonResult: NSDictionary! = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers ) as? NSDictionary339 340 if(httpResponse.url!.absoluteString != functionURL && httpResponse.statusCode > 301 ){341 self.deleteRequest(httpResponse.url!.absoluteString , deleteParams: deleteParams, callback: callback)342 return343 }344 345 if(jsonResult == nil)346 {347 callback(NSDictionary(),true)348 return;349 }350 351 if(jsonResult["error"] != nil )352 {353 if(jsonResult ["error"] as?String == "invalid_token") {354 355 JsapiAPi.sharedInstance.sessionExpired()356 357 callback(jsonResult,false)358 359 }else{360 361 if ((jsonResult["error"] as? NSDictionary) != nil) {362 363 let errorObject = jsonResult["error"] as! Dictionary<String,Bool>364 let isSuccess=errorObject["success"]365 callback(jsonResult,isSuccess!)366 }else{367 368 callback(jsonResult,false)369 }370 371 372 }373 }else374 {375 callback(jsonResult,true)376 }377 }) 378 task.resume()379 }380 //381 /**382 putRequest383 @param functionURL : function URL Example http://localhost:8080/jsapi/oauth/token384 @param postParams : post string385 @param isJson should sent true in case of json request386 @param callback block called once you got the response387 */388 func putRequest(_ functionURL:String,postParams:String,isJson:Bool,callback:@escaping (NSDictionary,Bool)->Void)389 {390 let request = NSMutableURLRequest(url: URL(string: functionURL)!)391 request.httpMethod = "PUT"392 let postString = postParams393 request.httpBody = postString.data(using: String.Encoding.utf8)394 if(isJson)395 {396 request.setValue("application/json", forHTTPHeaderField: "Content-Type")397 request.setValue("application/json", forHTTPHeaderField: "Accept")398 if(!JsapiAPi.sharedInstance.getJsapiToken().isEmpty&&JsapiAPi.sharedInstance.getJsapiToken() != JSAPIConstant.TOKENBREAR){399 400 request.setValue(JsapiAPi.sharedInstance.getJsapiToken(),forHTTPHeaderField:"Authorization")401 402 }403 404 }else{405 406 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")407 }408 409 self.requests[functionURL] = request410 411 let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)412 413 414 let task = session.dataTask(with: request as URLRequest , completionHandler: {415 data, response, error in416 if error != nil {417 418 var res = NSMutableDictionary();419 res.setValue(JSAPIConstant.CONNECTION_ERROR, forKey: "message")420 callback(res,false)421 return422 }423 424 // self.requests.removeValueForKey(request.URL!.absoluteString)425 426 let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)427 428 let httpResponse = response as! HTTPURLResponse429 430 431 if(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 && (responseString as! String) .isEmpty)432 {433 callback(NSDictionary(),true)434 435 return436 }437 if(httpResponse.url!.absoluteString != functionURL && httpResponse.statusCode > 301 ){438 self.putRequest(httpResponse.url!.absoluteString , postParams: postParams, isJson: isJson, callback: callback)439 }440 if(responseString=="")441 {442 callback(NSDictionary(),true)443 return;444 }445 446 let jsonResult2: AnyObject! = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject!447 448 if(jsonResult2 == nil)449 {450 callback(NSDictionary(),false)451 return;452 }453 let jsonResult : NSDictionary = (jsonResult2 as?NSDictionary)!;454 455// if(jsonResult == nil)456// {457// callback(NSDictionary(),true)458// return;459// }460 461 if(jsonResult["error"] != nil || ( jsonResult["code"] != nil && jsonResult["code"] as?Int != 0 ) )462 {463 if(jsonResult ["error"] as?String == "invalid_token") {464 465 JsapiAPi.sharedInstance.sessionExpired()466 467 callback(jsonResult,false)468 469 }else{470 471 if ((jsonResult["error"] as? NSDictionary) != nil) {472 473 let errorObject = jsonResult["error"] as! Dictionary<String,Bool>474 475 let isSuccess=errorObject["success"]476 callback(jsonResult,isSuccess!)477 }else{478 479 callback(jsonResult,false)480 481 }482 }483 }else484 {485 callback(jsonResult,true)486 }487 488 }) 489 task.resume()490 }491 var taskWillPerformHTTPRedirection: ((Foundation.URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?492 493 func URLSession(_ session: Foundation.URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: (URLRequest?) -> Void){494 495 496 let originalUrl:String = (response.url?.absoluteString)!497 498 let redirectRequest: NSMutableURLRequest = self.requests[originalUrl]!499 500 redirectRequest.url = request.url501 502 completionHandler(redirectRequest as URLRequest)503 }504 505 506 507 //508 /**509 getRequet510 @param functionURL : function URL Example http://localhost:8080/jsapi/services/latest/carts/e9486b32-674511 @param callback block called once you got the response512 */513 func getRequestWithoutAuthorization(_ functionURL:String,postParams:String,callback:@escaping (NSDictionary,Bool)->Void)514 {515 516 var endpoint:String = functionURL + postParams517 518 endpoint = endpoint.replacingOccurrences(of: " ", with: "%20")519 520 let request = NSMutableURLRequest(url: URL(string: endpoint )!)521 request.httpMethod = "GET"522 request.setValue("application/json", forHTTPHeaderField: "Content-Type")523 request.setValue("application/json", forHTTPHeaderField: "Accept")524 525 526 self.requests[functionURL] = request527 528 let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)529 530 let task = session.dataTask(with: request as URLRequest, completionHandler: {531 data, response, error in532 if error != nil {533 534 var res = NSMutableDictionary();535 res.setValue(JSAPIConstant.CONNECTION_ERROR, forKey: "message")536 callback(res,false)537 return538 }539 540 let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)541 542 let httpResponse = response as! HTTPURLResponse543 544 if(httpResponse.statusCode == 301 || httpResponse.statusCode == 307 ){545 self.getRequest(httpResponse.url!.absoluteString , postParams: postParams,callback: callback)546 return;547 }548 549 if(data == nil || data?.count <= 0 ){550 551 callback(NSDictionary(),false)552 return;553 554 }555 556 let jsonResult2: AnyObject! = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject!557 558 if(jsonResult2 == nil)559 {560 callback(NSDictionary(),false)561 return;562 }563 564 565 let jsonResult:NSDictionary = (jsonResult2 as? NSDictionary)!566 567 568 569 if(jsonResult["error"] != nil )570 {571 if(jsonResult ["error"] as?String == "invalid_token") {572 573 JsapiAPi.sharedInstance.sessionExpired()574 575 callback(jsonResult,false)576 577 }else{578 579 if ((jsonResult["error"] as? NSDictionary) != nil) {580 581 let errorObject = jsonResult["error"] as! Dictionary<String,Bool>582 583 let isSuccess=errorObject["success"]584 callback(jsonResult,isSuccess!)585 }else{586 587 callback(jsonResult,false)588 589 }590 }591 }else592 {593 callback(jsonResult,true)594 }595 }) 596 task.resume()597 }598}...

Full Screen

Full Screen

DictionaryToModel.swift

Source:DictionaryToModel.swift Github

copy

Full Screen

1//2// DictionaryToModel.swift3// Swift3ExentionDemo4//5// Created by 麻阳 on 16/11/01.6// Copyright © 2016年 麻阳. All rights reserved.7//8import Foundation9@objc public protocol DicModelProtocol{10 static func keyObjectClassMapping() -> [String: String]?11}12extension NSObject{13 14 //dic: 要进行转换的字典15 class func objectWithKeyValues(dict: NSDictionary)->AnyObject?{16 if BaseFoundation.isClassFromFoundation(c: self) {17 18 return nil19 }20 21 let obj:AnyObject = self.init()22 var cls:AnyClass = self.classForCoder() //当前类的类型23 24 while("NSObject" != "\(cls)"){25 var count:UInt32 = 026 let properties = class_copyPropertyList(cls, &count) //获取属性列表27 for i in 0..<count{28 29 let property = properties?[Int(i)]30 31 32 var propertyType = String(cString:property_getAttributes(property)) //属性类型33 let propertyKey = String(cString:property_getName(property))34 35 if propertyKey == "description"{ continue } //description是计算型属性36 37 38 var value:AnyObject! = dict.object(forKey: propertyKey) as AnyObject!//取得字典中的值39 40 if value == nil {continue}41 42 let valueType = "\(value.classForCoder)" //字典中保存的值得类型43 if valueType == "NSDictionary"{ //1,值是字典。 这个字典要对应一个自定义的模型类并且这个类不是Foundation中定义的类型。44 let subModelStr:String! = BaseFoundation.getType(code: &propertyType)45 if subModelStr == nil{46 print("字典中的键\(propertyKey)和模型中的不匹配")47 assert(true)48 }49 if let subModelClass = NSClassFromString(subModelStr){50 value = subModelClass.objectWithKeyValues(dict:value as! NSDictionary) //递归51 52 }53 }else if valueType == "NSArray"{ //值是数组。 数组中存放字典。 将字典转换成模型。 如果协议中没有定义映射关系,就不做处理54 55 if self.responds(to: Selector("keyObjectClassMapping")) {56 if var subModelClassName = cls.keyObjectClassMapping()?[propertyKey]{ //子模型的类名称57 subModelClassName = BaseFoundation.bundlePath+"."+subModelClassName58 if let subModelClass = NSClassFromString(subModelClassName){59 value = subModelClass.objectArrayWithKeyValuesArray(array:value as! NSArray);60 61 }62 }63 }64 65 }66 67 obj.setValue(value, forKey: propertyKey)68 }69 free(properties) //释放内存70 cls = cls.superclass()! //处理父类71 }72 return obj73 }74 75 /**76 将字典数组转换成模型数组77 array: 要转换的数组, 数组中包含的字典所对应的模型类就是 调用这个类方法的类78 79 当数组中嵌套数组, 内部的数组包含字典,cls就是内部数组中的字典对应的模型80 */81 class func objectArrayWithKeyValuesArray(array: NSArray)->NSArray?{82 if array.count == 0{83 return nil84 }85 var result = [AnyObject]()86 for item in array{87 let type = "\(((item as AnyObject).classForCoder)!)"88 if type == "NSDictionary" || type == "Dictionary" || type == "NSMutableDictionary"{89 if let model = objectWithKeyValues(dict: item as! NSDictionary){90 result.append(model)91 92 }93 }else if type == "NSArray" || type == "Array" || type == "NSMutableArray"{94 if let model = objectArrayWithKeyValuesArray(array: item as! NSArray){95 result.append(model)96 }97 }else{98 result.append(item as AnyObject)99 }100 }101 if result.count==0{102 return nil103 }else{104 return result as NSArray?105 }106 }107}...

Full Screen

Full Screen

Foundation.NSDictionary

Using AI Code Generation

copy

Full Screen

1import Foundation2import Foundation3import Foundation4import Foundation5import Foundation6import Foundation7import Foundation8import Foundation9import Foundation10import Foundation11import Foundation12import Foundation13import Foundation14import Foundation15import Foundation16import Foundation17import Foundation18import Foundation19import Foundation20import Foundation21import Foundation22import Foundation23import Foundation24import Foundation25import Foundation26import Foundation27import Foundation28import Foundation

Full Screen

Full Screen

Foundation.NSDictionary

Using AI Code Generation

copy

Full Screen

1import Foundation2let dict = NSDictionary()3print(dict)4import Foundation5let dict = NSDictionary()6print(dict)7import Foundation8let dict = NSDictionary()9print(dict)10import Foundation11let dict = NSDictionary()12print(dict)13import Foundation14let dict = NSDictionary()15print(dict)16import Foundation17let dict = NSDictionary()18print(dict)19import Foundation20let dict = NSDictionary()21print(dict)22import Foundation23let dict = NSDictionary()24print(dict)25import Foundation26let dict = NSDictionary()27print(dict)28import Foundation29let dict = NSDictionary()30print(dict)31import Foundation32let dict = NSDictionary()33print(dict)34import Foundation35let dict = NSDictionary()36print(dict)37import Foundation38let dict = NSDictionary()39print(dict)40import Foundation41let dict = NSDictionary()42print(dict)43import Foundation44let dict = NSDictionary()45print(dict)46import Foundation47let dict = NSDictionary()48print(dict)49import Foundation50let dict = NSDictionary()51print(dict

Full Screen

Full Screen

Foundation.NSDictionary

Using AI Code Generation

copy

Full Screen

1import Foundation2class Foo {3 func bar() {4 let dict = NSDictionary()5 }6}7import Foundation8class Foo {9 func bar() {10 let dict = NSDictionary()11 }12}13Is there a way to specify which framework I want to use for a particular class? I know that in Objective-C I can use #import <Nimble/NSDictionary.h> to specify which framework to use. Is there a similar syntax in Swift?14clang: error: linker command failed with exit code 1 (use -v to see invocation)15clang: error: linker command failed with exit code 1 (use -v to see invocation)

Full Screen

Full Screen

Foundation.NSDictionary

Using AI Code Generation

copy

Full Screen

1import Foundation2import Nimble3var dict = NSDictionary()4expect(dict["key"]).to(equal("value"))5import Foundation6import Nimble7var dict = NSDictionary()8expect(dict["key"]).to(equal("value"))9import Foundation10import Nimble11var dict = NSDictionary()12expect(dict["key"]).to(equal("value"))13import Foundation14import Nimble15var dict = NSDictionary()16expect(dict["key"]).to(equal("value"))17import Foundation18import Nimble19var dict = NSDictionary()20expect(dict["key"]).to(equal("value"))21import Foundation22import Nimble23var dict = NSDictionary()24expect(dict["key"]).to(equal("value"))25import Foundation26import Nimble27var dict = NSDictionary()28expect(dict["key"]).to(equal("value"))29import Foundation30import Nimble31var dict = NSDictionary()32expect(dict["key"]).to(equal("value"))33import Foundation34import Nimble35var dict = NSDictionary()36expect(dict["key"]).to(equal("value"))37import Foundation38import Nimble39var dict = NSDictionary()40expect(dict["key"]).to(equal("value"))

Full Screen

Full Screen

Foundation.NSDictionary

Using AI Code Generation

copy

Full Screen

1import Foundation2class Foo {3 init(bar: String) {4 }5}6var dict = [String: Foo]()7dict["foo"] = Foo(bar: "bar")8print(foo.bar)9import Foundation10class Foo {11 init(bar: String) {12 }13}14var dict = [String: Foo]()15dict["foo"] = Foo(bar: "bar")16print(foo.bar)17import Foundation18class Foo {19 init(bar: String) {20 }21}22var dict = [String: Foo]()23dict["foo"] = Foo(bar: "bar")24print(foo.bar)25import Foundation26class Foo {27 init(bar: String) {28 }29}30var dict = [String: Foo]()31dict["foo"] = Foo(bar: "bar")32print(foo.bar)33import Foundation34class Foo {35 init(bar: String) {36 }37}38var dict = [String: Foo]()39dict["foo"] = Foo(bar: "bar")40print(foo.bar)41import Foundation42class Foo {43 init(bar: String) {44 }45}46var dict = [String: Foo]()47dict["foo"] = Foo(bar: "bar")48print(foo.bar)49import Foundation50class Foo {51 init(bar: String) {52 }53}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nimble automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful