Commit 4a6dc266 by lee

u 购物车基本修改完成

parent 3c1a8678
......@@ -2,11 +2,15 @@
platform :ios, '8.0'
# Uncomment this line if you're using Swift
# use_frameworks!
inhibit_all_warnings!
target 'iCemarose' do
# CordovaLib Dependency Pod
#pod 'Cordova'
pod 'JRSwizzle'
pod 'RegexKitLite'
pod 'SAMKeychain'
pod 'AFNetworking','~> 2.6'
pod 'JSONModel','~> 1.2.0'
......
......@@ -83,6 +83,10 @@
80F82E611D704E34008B470B /* KWMBrandCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 80F82E5F1D704E34008B470B /* KWMBrandCell.m */; };
80F82E621D704E34008B470B /* KWMBrandCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 80F82E601D704E34008B470B /* KWMBrandCell.xib */; };
80FBF7E18C063DB9E8DC7502 /* libPods-iCemarose.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 450DA8BB947651E9A9B38BEB /* libPods-iCemarose.a */; };
9B0F56B81ECD3424009FC5FE /* UIViewController+AppearLog.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B0F56B71ECD3424009FC5FE /* UIViewController+AppearLog.m */; };
9BE61CFB1ECD56E70031D21E /* KWMDictioaryResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 9BE61CFA1ECD56E70031D21E /* KWMDictioaryResult.m */; };
9BE61CFE1ECD66BC0031D21E /* KWMShoppingCart.m in Sources */ = {isa = PBXBuildFile; fileRef = 9BE61CFD1ECD66BC0031D21E /* KWMShoppingCart.m */; };
9BE61D011ECD71610031D21E /* KWMCartResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 9BE61D001ECD71610031D21E /* KWMCartResult.m */; };
C001BA5C1EB2ED5500B366A8 /* KWMImageBlurUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = C001BA5B1EB2ED5500B366A8 /* KWMImageBlurUtil.m */; };
C0219A951DF53EB200711099 /* KWMExchangeRateResult.m in Sources */ = {isa = PBXBuildFile; fileRef = C0219A941DF53EB200711099 /* KWMExchangeRateResult.m */; };
C02C7D801E640D82008DC29C /* libWeChatSDK.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C02C7D7B1E640D82008DC29C /* libWeChatSDK.a */; };
......@@ -415,7 +419,15 @@
80F82E5E1D704E34008B470B /* KWMBrandCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KWMBrandCell.h; sourceTree = "<group>"; };
80F82E5F1D704E34008B470B /* KWMBrandCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KWMBrandCell.m; sourceTree = "<group>"; };
80F82E601D704E34008B470B /* KWMBrandCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = KWMBrandCell.xib; sourceTree = "<group>"; };
9B0F56B61ECD3424009FC5FE /* UIViewController+AppearLog.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIViewController+AppearLog.h"; sourceTree = "<group>"; };
9B0F56B71ECD3424009FC5FE /* UIViewController+AppearLog.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIViewController+AppearLog.m"; sourceTree = "<group>"; };
9B58353B797587723B0E7515 /* Pods-iCemarose.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iCemarose.debug.xcconfig"; path = "Pods/Target Support Files/Pods-iCemarose/Pods-iCemarose.debug.xcconfig"; sourceTree = "<group>"; };
9BE61CF91ECD56E70031D21E /* KWMDictionaryResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KWMDictionaryResult.h; sourceTree = "<group>"; };
9BE61CFA1ECD56E70031D21E /* KWMDictioaryResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KWMDictioaryResult.m; sourceTree = "<group>"; };
9BE61CFC1ECD66BC0031D21E /* KWMShoppingCart.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KWMShoppingCart.h; sourceTree = "<group>"; };
9BE61CFD1ECD66BC0031D21E /* KWMShoppingCart.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KWMShoppingCart.m; sourceTree = "<group>"; };
9BE61CFF1ECD71610031D21E /* KWMCartResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KWMCartResult.h; sourceTree = "<group>"; };
9BE61D001ECD71610031D21E /* KWMCartResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KWMCartResult.m; sourceTree = "<group>"; };
B5C3F0326028FE5E2F51B4C1 /* Pods-iCemarose.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iCemarose.release.xcconfig"; path = "Pods/Target Support Files/Pods-iCemarose/Pods-iCemarose.release.xcconfig"; sourceTree = "<group>"; };
C001BA5A1EB2ED5500B366A8 /* KWMImageBlurUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KWMImageBlurUtil.h; sourceTree = "<group>"; };
C001BA5B1EB2ED5500B366A8 /* KWMImageBlurUtil.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KWMImageBlurUtil.m; sourceTree = "<group>"; };
......@@ -1022,6 +1034,8 @@
807806841D75666400FD2841 /* Classify */,
C034E6C51D6AECF9006EE129 /* View */,
80ED0A3D1D93B4CF00B28DF2 /* CoreData */,
9B0F56B61ECD3424009FC5FE /* UIViewController+AppearLog.h */,
9B0F56B71ECD3424009FC5FE /* UIViewController+AppearLog.m */,
);
path = Class;
sourceTree = "<group>";
......@@ -1078,6 +1092,8 @@
C0F4AF4A1DF1149500BDA719 /* KWMProduct.m */,
C0D7CA9F1EA843AD005AE3A3 /* KWMOrder.h */,
C0D7CAA01EA843AD005AE3A3 /* KWMOrder.m */,
9BE61CFC1ECD66BC0031D21E /* KWMShoppingCart.h */,
9BE61CFD1ECD66BC0031D21E /* KWMShoppingCart.m */,
);
path = Model;
sourceTree = "<group>";
......@@ -1613,6 +1629,10 @@
C0219A941DF53EB200711099 /* KWMExchangeRateResult.m */,
C0D7CAA21EA846AA005AE3A3 /* KWMOrdersResult.h */,
C0D7CAA31EA846AA005AE3A3 /* KWMOrdersResult.m */,
9BE61CF91ECD56E70031D21E /* KWMDictionaryResult.h */,
9BE61CFA1ECD56E70031D21E /* KWMDictioaryResult.m */,
9BE61CFF1ECD71610031D21E /* KWMCartResult.h */,
9BE61D001ECD71610031D21E /* KWMCartResult.m */,
);
path = Cemarose;
sourceTree = "<group>";
......@@ -2011,7 +2031,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
F84386F9A53E1205C21D5570 /* [CP] Copy Pods Resources */ = {
......@@ -2049,6 +2069,7 @@
C034E7001D6AF205006EE129 /* KWMButton.m in Sources */,
C0F5867A1E24F820001248E2 /* KWMDoubleTitleView.m in Sources */,
8091DFBB1D6EC1DD0020519C /* KWMThreeView.m in Sources */,
9BE61CFB1ECD56E70031D21E /* KWMDictioaryResult.m in Sources */,
C034E6D81D6AEF1B006EE129 /* KWMImageUtil.m in Sources */,
C03846941DB89EEB008C3BAB /* KWMCemaroseResult.m in Sources */,
C0F586951E25C17A001248E2 /* KWMProductDetailVC.m in Sources */,
......@@ -2086,6 +2107,7 @@
C034E85C1D6B10A0006EE129 /* UIView+PBExtend.m in Sources */,
C0F5867E1E24F820001248E2 /* KWMNewGoodsCell.m in Sources */,
C032D3071DD87E5F008D3155 /* KWMImage.m in Sources */,
9BE61CFE1ECD66BC0031D21E /* KWMShoppingCart.m in Sources */,
C0F586761E24F820001248E2 /* KWMCollectionCell.m in Sources */,
C034E8421D6B10A0006EE129 /* NSArray+Extend.m in Sources */,
C034E85B1D6B10A0006EE129 /* LFRoundProgressView.m in Sources */,
......@@ -2132,6 +2154,7 @@
C034E8401D6B10A0006EE129 /* CALayer+Anim.m in Sources */,
C0FC278E1D9B73B000C5CFFE /* KWMGiftCardCell.m in Sources */,
8077F79A1D73E39000A2E2E2 /* KWMBrandCaramelCell.m in Sources */,
9BE61D011ECD71610031D21E /* KWMCartResult.m in Sources */,
C084F4571D6D975400A0625D /* KWMSearchBar.m in Sources */,
C0F586841E24F820001248E2 /* KWMWatchView.m in Sources */,
C0E8AE091D7D030B00C193DC /* KWMEditAddressVC.m in Sources */,
......@@ -2177,6 +2200,7 @@
C034E8441D6B10A0006EE129 /* NSObject+Extend.m in Sources */,
8079FF701D797DDC0037A71F /* KWMPointView.m in Sources */,
80A611B21D6DB0EC00709E09 /* KWMShopCartVC.m in Sources */,
9B0F56B81ECD3424009FC5FE /* UIViewController+AppearLog.m in Sources */,
C034E8451D6B10A0006EE129 /* NSString+Extend.m in Sources */,
805C04381DD1FA7100ACC071 /* KWMBrandsTypeResult.m in Sources */,
C034E6DA1D6AEF1B006EE129 /* KWMTextFieldUtil.m in Sources */,
......
//
// KWMCartResult.h
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import "KWMCemaroseResult.h"
#import "KWMShopCartModel.h"
@interface KWMCartResult : KWMCemaroseResult
@property (nonatomic, strong) NSNumber *original_total_price;
@property (nonatomic, strong) NSNumber *total_price;
@property (nonatomic, strong) NSNumber *total_discount;
@property (nonatomic, strong) NSNumber *item_count;
@property (nonatomic, assign) BOOL requires_shipping;
@property (nonatomic, strong) NSArray<KWMShopCartModel *> *items;
@end
//
// KWMCartResult.m
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import "KWMCartResult.h"
#import "KWMImageUtil.h"
@implementation KWMCartResult
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
self = [super initWithDictionary:dict error:err];
if (self) {
NSArray *dataArray = dict[@"items"];
if(dataArray){
self.items = [self buildListData:[KWMShopCartModel class] jsonDictionary:dataArray];
}
}
return self;
}
- (instancetype)initWithDictionary:(NSDictionary *)dict modelClass:(Class)modelClass error:(NSError *__autoreleasing *)err {
if (self = [super initWithDictionary:dict error:err]) {
NSArray *dataArray = dict[@"items"];
if(dataArray){
self.items = [self buildListData:[KWMShopCartModel class] jsonDictionary:dataArray];
}
}
return self;
}
- (NSArray *)buildListData:(Class)modelClass jsonDictionary:(NSArray *)dataArray {
NSMutableArray *datas = [NSMutableArray arrayWithCapacity:dataArray.count];
for (id item in dataArray) {
KWMShopCartModel *shopCartModel = [[KWMShopCartModel alloc] init];
shopCartModel.name = item[@"title"];
shopCartModel.brand = item[@"vendor"];
shopCartModel.identifier = [item[@"id"] stringValue];
shopCartModel.size = item[@"variant_title"];
shopCartModel.product_id = item[@"product_id"];
shopCartModel.quantity = [item[@"quantity"] integerValue];
shopCartModel.price = [item[@"discounted_price"] floatValue] / 100;
shopCartModel.imageStr = [KWMImageUtil getProductImageUrl:item[@"product_id"] ImageSize:NormalImage];
shopCartModel.shopCartDict = item;
[datas addObject:shopCartModel];
}
return datas;
}
@end
//
// KWMDictiomaryResult.m
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import "KWMDictionaryResult.h"
@implementation KWMDictionaryResult
- (instancetype)initWithDictionary:(NSDictionary *)dict
modelClass:(Class)modelClass
error:(NSError **)err {
if (self = [super init]) {
self.data = dict;
}
return self;
}
@end
//
// KWMDictiomaryResult.h
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import "KWMCemaroseResult.h"
@interface KWMDictionaryResult : KWMCemaroseResult
@property (nonatomic, strong) NSDictionary *data;
@end
......@@ -28,7 +28,7 @@
#import "KWMOrdersResult.h"
#import "KWMOrder.h"
#import "KWMExchangeRateResult.h"
#import "KWMCartResult.h"
......@@ -62,6 +62,46 @@
success:(void(^)(NSURLSessionDataTask *task,KWMCemaroseResult *result))success
failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure;
/**
* 登陆网站接口
*
* @param success <#success description#>
* @param failure <#failure description#>
*/
- (void) loginWebSuccess:(void(^)()) success failure:(void(^)(NSError *error)) failure;
/**
* 添加商品到购物车
*
* @param variantId <#variantId description#>
* @param quantity <#quantity description#>
* @param success <#success description#>
* @param failure <#failure description#>
*
* @return <#return value description#>
*/
- (NSURLSessionDataTask *) addProductWithVariantId:(NSNumber *) variantId quantity:(NSInteger) quantity success:(void(^)(NSURLSessionDataTask *task,KWMRequestResult *result)) success failure:(void(^)(NSURLSessionDataTask *task,NSError *error)) failure;
/**
*
*
* @param variantId <#variantId description#>
* @param success <#success description#>
* @param failure <#failure description#>
*
* @return <#return value description#>
*/
- (NSURLSessionDataTask *) updateProductWithVariantId:(NSNumber *) variantId quantity:(NSInteger) quantity success:(void(^)(NSURLSessionDataTask *task,KWMCartResult *result)) success failure:(void(^)(NSURLSessionDataTask *task,NSError *error)) failure;
/**
* 获取系统购物车
*
* @param success <#success description#>
* @param failure <#failure description#>
*
* @return <#return value description#>
*/
- (NSURLSessionDataTask *) getCartSuccess:(void(^)(NSURLSessionDataTask *task,KWMCartResult *result)) success failure:(void(^)(NSURLSessionDataTask *task,NSError *error)) failure;
/**
* 手机登录API
* @param parameters {mobile=?手机号,code=?收到的短信验证码}
......
......@@ -19,6 +19,10 @@
#import "KWMCustomerResult.h"
#import "KWMBrandsTypeResult.h"
#import "KWMBrandsTypeModel.h"
#import "KWMDictionaryResult.h"
#import <RegexKitLite/RegexKitLite.h>
#import <SAMKeychain/SAMKeychain.h>
#import "KWMUserModel.h"
......@@ -74,9 +78,9 @@ typedef NS_ENUM(NSInteger, KWMHTTPMethod) {
id result = nil;
@try {
//#ifdef DEBUG
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
// NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
// NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(@"%@", jsonString);
//#endif
result = [[requestResultClass alloc] initWithDictionary:jsonDict modelClass:modelClass error:&error];
}
......@@ -170,7 +174,8 @@ static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";
sessionManager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:0];
}
[[KWMUserDao shareDao] checkSession];
// 使用系统cookie管理 2017年5月18日 因为改动cart需要使用cookie
// [[KWMUserDao shareDao] checkSession];
sessionManager.requestSerializer.HTTPShouldHandleCookies = YES;
sessionManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
......@@ -186,6 +191,7 @@ static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";
}
- (NSURLSessionDataTask *)startSessionTask:(KWMHTTPMethod)httpMethod
apiPath:(NSString *)apiPath
parameters:(NSDictionary *)parameters
......@@ -210,13 +216,13 @@ static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";
failure:failure];
AFHTTPSessionManager *sessionManager = [self buildSessionManager:isJsonParameter];
//app version code
static NSString *KEY_VERSION_CODE = @"version_code";
NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
// static NSString *KEY_VERSION_CODE = @"version_code";
// NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
NSMutableDictionary *mutableParameters = [[NSMutableDictionary alloc] initWithDictionary:parameters];
// mutableParameters[KEY_VERSION_CODE] = build;
//os_version统一添加
static NSString *KEY_OS_VERSION = @"os_version";
// static NSString *KEY_OS_VERSION = @"os_version";
// mutableParameters[KEY_OS_VERSION] = [NSString stringWithFormat:@"ios%@", [UIDevice currentDevice].systemVersion];
// NSLog(@"os_version:%@=====", mutableParameters[KEY_OS_VERSION]);
......@@ -298,6 +304,7 @@ static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";
}
- (NSURLSessionDataTask *)startSessionTask:(KWMHTTPMethod)httpMethod
apiPath:(NSString *)apiPath
parameters:(NSDictionary *)parameters
......@@ -351,7 +358,43 @@ static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";
}
}
- (void)loginWebSuccess:(void (^)())success failure:(void (^)(NSError *))failure {
KWMUserModel *user= [KWMUserModel shareUser];
NSString *account = user.email;
NSString *password = user.password;
if (!password) {
password = [SAMKeychain passwordForService:@"cemarose.account" account:account];
}
// 没登陆过不做处理
if (!password) {
return;
}
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
NSString *url = request.URL.absoluteString;
if ([url isEqualToString:[NSString stringWithFormat:@"https://%@/account",Shopify_SHOP_DOMAIN]]) {
success();
}else{
NSError *error = [[NSError alloc] initWithDomain:url code:401 userInfo:@{NSLocalizedDescriptionKey:@"email & password is invalid !"}];
failure(error);
}
return nil;
}];
NSString *loginUrl = [NSString stringWithFormat:@"https://%@/account/login",Shopify_SHOP_DOMAIN];
id param = @{
@"from_type":@"customer_login",
@"utf8":@"✓",
@"customer[email]":account,
@"customer[password]":password,
};
[manager POST:loginUrl parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
/**
* 手机登录API
......@@ -375,6 +418,25 @@ static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";
failure:failure];
}
- (NSURLSessionDataTask *)updateProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger) quantity success:(void (^)(NSURLSessionDataTask *, KWMCartResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart/change/%@.js",Shopify_SHOP_DOMAIN,variantId];
id params = @{ @"quantity": @(quantity) };
return [self startSessionTask:KWMHTTPMethodGET apiPath:apiPath parameters:params result:[KWMCartResult class] model:nil success:success failure:failure];
}
- (NSURLSessionDataTask *)addProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity success:(void (^)(NSURLSessionDataTask *, KWMRequestResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart/add.js",Shopify_SHOP_DOMAIN];
id params = @{
@"id":variantId,
@"quantity":@(quantity),
};
return [self startSessionTask:KWMHTTPMethodPOST apiPath:apiPath parameters:params result:[KWMDictionaryResult class] model:nil success:success failure:failure];
}
-(NSURLSessionDataTask *)getCartSuccess:(void (^)(NSURLSessionDataTask *, KWMCartResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart.js",Shopify_SHOP_DOMAIN];
return [self startSessionTask:KWMHTTPMethodGET apiPath:apiPath parameters:nil result:[KWMCartResult class] model:nil success:success failure:failure];
}
/**
* 手机登录-获取短信API
......
......@@ -15,7 +15,7 @@
- (instancetype)initWithDictionary:(NSDictionary *)dict
modelClass:(Class)modelClass
error:(NSError **)err {
self = [super initWithDictionary:dict error:err];
self = [super initWithDictionary:@{@"message":@"",@"code":@"",@"data":dict} error:err];
if (self) {
NSDictionary *dataDictionary = dict[@"data"];
if(dataDictionary){
......
......@@ -13,6 +13,13 @@
@interface KWMShopCartData : NSObject
/**
* 商品同步 会清除已有的然后重新保存
*
* @param items <#items description#>
*/
- (void)syncCartProducts:(NSArray *) items;
//添加购物商品
- (void) inocreaseItem:(KWMShopCartModel *)shopCartModel;
......
......@@ -10,6 +10,13 @@
#define KWM_MAX_PRODUCT_COUNT 9999
@implementation KWMShopCartData
-(void)syncCartProducts:(NSArray *)items {
[self removeAllItems];
for (KWMShopCartModel *item in items) {
[self inocreaseItem:item];
}
}
//添加购物商品
- (void) inocreaseItem:(KWMShopCartModel *)shopCartModel{
KWMShopCartItem *shopCartItem = [self toShopCartProduct:shopCartModel];
......
......@@ -14,6 +14,7 @@
@property (nullable, nonatomic, copy) NSString *brand;
@property (nullable, nonatomic, copy) NSString *name;
@property (nullable, nonatomic, copy) NSString *size;
@property (nullable, nonatomic, strong) NSNumber *product_id;
@property (nonatomic) NSInteger quantity;
@property (nonatomic) float price;
@property (nullable, nonatomic, retain) NSDictionary *shopCartDict;
......
//
// KWMShoppingCart.h
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "KWMShopCartModel.h"
#import "KWMCartResult.h"
typedef void(^ShoppingCartCallBack) (NSError *error,KWMCartResult *cart);
@interface KWMShoppingCart : NSObject
@property (nonatomic, strong) NSMutableArray<KWMShopCartModel *> * items;
+ (instancetype)sharedInstance;
- (void)allItemsWithCallback:(ShoppingCartCallBack) callback;
- (void)increaseProductWithVariantId:(NSNumber *) variantId quantity:(NSInteger) quantity callback:(ShoppingCartCallBack) callback;
- (void)updateProductWithVariantId:(NSNumber *) variantId quantity:(NSInteger) quantity callback:(ShoppingCartCallBack) callback;
- (void)deleteProductWithVariantId:(NSNumber *) variantId callback:(ShoppingCartCallBack) callback;
@end
//
// KWMShoppingCart.m
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import "KWMShoppingCart.h"
#import "KWMCartResult.h"
#import "KWMShopCartData.h"
@interface KWMShoppingCart ()
@property (nonatomic, strong) KWMCartResult *result;
@end
@implementation KWMShoppingCart
- (NSMutableArray<KWMShopCartModel *> *)items {
return (NSMutableArray *)_result.items;
}
- (void)setResult:(KWMCartResult *)result {
_result = result;
[[KWMShopCartData alloc] syncCartProducts:result.items];
}
+ (instancetype)sharedInstance {
static KWMShoppingCart *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
instance = [[super allocWithZone:NULL] init];
});
return instance;
}
- (void)allItemsWithCallback:(ShoppingCartCallBack)callback {
[[KWMAPIManager sharedManager] getCartSuccess:^(NSURLSessionDataTask *task, KWMCartResult *result) {
[[KWMShoppingCart sharedInstance] setResult:result];
callback(nil,result);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
callback(error,nil);
}];
}
- (void)increaseProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity callback:(ShoppingCartCallBack)callback {
[[KWMAPIManager sharedManager] addProductWithVariantId:variantId quantity:quantity success:^(NSURLSessionDataTask *task, KWMRequestResult *result) {
[[KWMShoppingCart sharedInstance] allItemsWithCallback:^(NSError *error, KWMCartResult *cart) {
callback(error,cart);
}];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
callback(error,nil);
}];
}
- (void)updateProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity callback:(ShoppingCartCallBack)callback {
[[KWMAPIManager sharedManager] updateProductWithVariantId:variantId quantity:quantity success:^(NSURLSessionDataTask *task, KWMCartResult *result) {
[[KWMShoppingCart sharedInstance] setResult:result];
callback(nil,result);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
callback(error,nil);
}];
}
- (void)deleteProductWithVariantId:(NSNumber *)variantId callback:(ShoppingCartCallBack)callback {
[self updateProductWithVariantId:variantId quantity:0 callback:callback];
}
+ (id)allocWithZone:(struct _NSZone *)zone {
return [KWMShoppingCart sharedInstance];
}
- (id)copy {
return self;
}
- (id)mutableCopy {
return self;
}
@end
......@@ -17,6 +17,7 @@
@property (nonatomic) NSDictionary *tokenJSON;
+ (instancetype)shareUser;
+ (void) saveAccountByCredentials:(BUYAccountCredentials *) credentials;
- (void)login;
- (void)logout;
@end
......@@ -7,6 +7,7 @@
//
#import "KWMUserModel.h"
#import <SAMKeychain/SAMKeychain.h>
@implementation KWMUserModel
......@@ -64,6 +65,18 @@ static KWMUserModel *_shareUser;
[self deleteUser];
}
+ (void) saveAccountByCredentials:(BUYAccountCredentials *) credentials {
NSString *account = nil,*password = nil;
for (BUYAccountCredentialItem *item in credentials.items) {
if ([item.key isEqualToString:BUYAccountEmailKey]) {
account = item.value.lowercaseString;
} else if ([item.key isEqualToString:BUYAccountPasswordKey]) {
password = item.value;
}
}
[SAMKeychain setPassword:password forService:@"cemarose.account" account:account];
}
- (void)deleteUser{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"KeyUser"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"customer"];
......
......@@ -16,6 +16,7 @@
#import "KWMBlogDetailVC.h"
#import "KWMUserModel.h"
#import "KWMLoginVC.h"
#import "KWMShoppingCart.h"
@interface KWMHomeVC ()
@property (nonatomic)KWMSearchBar *searchBar;
......@@ -42,6 +43,13 @@
[super viewDidLoad];
_dataArr = [NSArray array];
[self requestBlogAPI];
[self.api loginWebSuccess:^{
// [[KWMShoppingCart sharedInstance] allItemsWithCallback:^(NSError *error, KWMCartResult *cart) {
//
// }];
} failure:^(NSError *error) {
}];
}
- (UITableView *)targetTableView{
......
......@@ -167,9 +167,10 @@
//请求登录aip
- (void)requestLoginAPI{
BUYAccountCredentials *bac = credentials;
[self.client loginCustomerWithCredentials:credentials callback:^(BUYCustomer * _Nullable customer, BUYCustomerToken * _Nullable token, NSError * _Nullable error) {
if (customer && token && !error) {
[KWMUserModel saveAccountByCredentials:bac];
_customer = customer;
_token = token;
_userModel.customerJSON = customer.JSONDictionary;
......
......@@ -431,6 +431,7 @@
[self.client loginCustomerWithCredentials:credentials callback:^(BUYCustomer * _Nullable customer, BUYCustomerToken * _Nullable token, NSError * _Nullable error) {
[self hideLoading];
if (customer && token && !error) {
[KWMUserModel saveAccountByCredentials:credentials];
_customer = customer;
_token = token;
_userModel.customerJSON = customer.JSONDictionary;
......
......@@ -60,6 +60,7 @@ static NSString * idStr = @"KWMNewGoodsCell";
isNew = YES;
[self initView];
[self requestNewProductsCollection];
}
- (void)initNotification{
......
......@@ -23,6 +23,7 @@
#import "MZFormSheetPresentationViewController.h"
#import "KWMShareVC.h"
#import "KWMImageUtil.h"
#import "KWMShoppingCart.h"
......@@ -168,7 +169,8 @@
KWMSelectSizeVC *editVC = (KWMSelectSizeVC *)[KWMBaseVC findControllerBy:[KWMSelectSizeVC kwmTag] fromStoryboard:@"ShopCart"];
editVC.delegate = self;
editVC.product = self.product;
NSDictionary *shopCartDict = self.product.JSONDictionary;
// NSDictionary *shopCartDict = self.product.JSONDictionary;
editVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
editVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
editVC.providesPresentationContextTransitionStyle = YES;
......@@ -210,6 +212,22 @@
[self initRecommendProduct];
}
#pragma mark - KWMSelectSizeVCDelegate
- (void)kwm_addShopWithVariantId:(NSNumber *)identifier quantity:(NSInteger)quantity buyNow:(BOOL)buyNow callback:(void (^)(BOOL))callback {
__weak KWMProductDetailVC *this = self;
[[KWMShoppingCart sharedInstance] increaseProductWithVariantId:identifier quantity:quantity callback:^(NSError *error, KWMCartResult *cart) {
if (!error) {
[this showToast:@"添加成功"];
[this.btnShopCart setTitle:cart.item_count.stringValue forState:UIControlStateNormal];
callback(YES);
}else{
[this showError:error];
callback(NO);
}
}];
}
//KWMSelectSizeVCDelegate
-(void)kwm_addShopCartItem:(KWMShopCartModel *)shopCartModel{
[self initShopCartCount];
......@@ -232,6 +250,8 @@
}
}
#pragma mark - KWMSelectSizeVCDelegate End
-(void)initRecommendProduct{
if(self.product == nil){
return;
......
......@@ -17,7 +17,7 @@
#import "KWMPaySuccessVC.h"
#import "KWMStringUtil.h"
#import "UIColor+SAMAdditions.h"
#import <RegexKitLite/RegexKitLite.h>
@interface KWMBeforePayVC ()
......@@ -213,18 +213,28 @@
//初始化订单
-(void)initCheckOut{
[self initBuyCart];
// 直接使用session cart所以不需要init了之后可以做代码清除
// [self initBuyCart];
//如果已登录
if(self.cart && self.customer){
// if(self.cart && self.customer){
if(self.customer){
BUYCheckout *checkout = nil;
//如果self.checkout1=nil,则为缓存订单,反正则为新建订单
// BUYCheckout *checkout = nil;
// //如果self.checkout1=nil,则为缓存订单,反正则为新建订单
// NSDictionary *checkoutCache = [self.userDao checkOutCache];
// // 这个if可能不需要了 下面下直接对session进行修改就可以
// if(checkoutCache){
// // update server
// checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:checkoutCache];
// [checkout updateWithCart:self.cart];
// }else{
// // init checkout 这里应该也没用了 因为self.cart不存在
// checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager cart:self.cart];
// }
NSDictionary *checkoutCache = [self.userDao checkOutCache];
if(checkoutCache){
checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:checkoutCache];
[checkout updateWithCart:self.cart];
}else{
checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager cart:self.cart];
BUYCheckout *checkout = nil;
if (!checkoutCache) {
checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:nil];
}
if(self.address){
if([self checkAddress:self.address]){
......@@ -245,11 +255,15 @@
}
checkout.email = self.customer.email;
// self.client.urlScheme = @"CemaroseApp://";
if(checkoutCache){
[self requestUpdateCheckout:checkout isCacheCheckout:YES];
}else{
[self requestCreateCheckout:checkout];
}
// 走session的情况下应该不存在update 只是update cart自动会update到checkout
// if(checkoutCache){
// 更新订单
// [self requestUpdateCheckout:checkout isCacheCheckout:YES];
// }else{
// 申请将session cart转成checkout
[self requestCreateCheckout:checkout];
//
// }
}
}
......@@ -384,24 +398,62 @@
-(void)requestCreateCheckout:(BUYCheckout *)checkout{
[self showLoading];
//[self showToast:@"创建订单中"];
__weak KWMBeforePayVC *weakSelf = self;
self.checkoutCreationOperation = [self.client createCheckout:checkout completion:^(NSDictionary *dictionary,BUYCheckout *checkout, NSError *error) {
[self hideLoading];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (error == nil && checkout) {
weakSelf.checkout = checkout;
//[self showToast:@"创建订单成功"];
[weakSelf initData];
NSLog(@"saveDict: %@",dictionary);
[weakSelf.userDao saveCheckoutCache:dictionary];
if(weakSelf.checkout.shippingAddress!=nil){
[weakSelf requestShippingData];
}}
else {
[self hideLoading];
[weakSelf showError:error];
NSLog(@"Error creating checkout: %@", error);
// __weak KWMBeforePayVC *weakSelf = self;
// self.checkoutCreationOperation = [self.client createCheckout:checkout completion:^(NSDictionary *dictionary,BUYCheckout *checkout, NSError *error) {
// [self hideLoading];
// [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
// if (error == nil && checkout) {
// weakSelf.checkout = checkout;
// //[self showToast:@"创建订单成功"];
// [weakSelf initData];
// NSLog(@"saveDict: %@",dictionary);
// [weakSelf.userDao saveCheckoutCache:dictionary];
// if(weakSelf.checkout.shippingAddress!=nil){
// [weakSelf requestShippingData];
// }}
// else {
// [self hideLoading];
// [weakSelf showError:error];
// NSLog(@"Error creating checkout: %@", error);
// }
// }];
__weak KWMBeforePayVC *this = self;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
if (!response) {
return request;
}
NSString *checkoutId = [request.URL.absoluteString stringByMatching:@"checkouts/(.*?)\\?" capture:1];
checkoutId = checkoutId ? checkoutId : [request.URL.absoluteString stringByMatching:@"checkouts/(.*)$" capture:1];
NSString *URLString = [NSString stringWithFormat:@"https://%@/api/checkouts/%@.json",Shopify_SHOP_DOMAIN,checkoutId];
NSMutableURLRequest *newReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
[newReq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[newReq setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSString *token = [NSString stringWithFormat:@"Basic %@",[[this.client.apiKey dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]];
[newReq setValue:token forHTTPHeaderField:@"Authorization"];
if(this.client.customerToken) {
[newReq setValue:this.client.customerToken.accessToken forHTTPHeaderField:@"X-Shopify-Customer-Access-Token"];
}
// 如果有checkout说明是新订单 直接更新订单地址就好 如果没有checkout说明是旧订单已经有地址所以无需更新
if (checkout) {
newReq.HTTPMethod = @"PATCH";
[newReq setHTTPBody:[NSJSONSerialization dataWithJSONObject:[checkout jsonDictionaryForCheckout] options:0 error:nil]];
}
return newReq;
}];
[manager GET:[NSString stringWithFormat:@"https://%@/checkout",Shopify_SHOP_DOMAIN] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
[this hideLoading];
BUYCheckout *checkout = [this.client.modelManager insertCheckoutWithJSONDictionary:responseObject[@"checkout"]];
this.checkout = checkout;
[this initData];
[this.userDao saveCheckoutCache:responseObject[@"checkout"]];
if(!this.checkout.shippingAddress) {
[this requestShippingData];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[this showError:error];
}];
}
......
......@@ -19,6 +19,8 @@
- (void)kwm_fastBuy:(BUYCart *)fastBuyCart;
- (void)kwm_addShopWithVariantId:(NSNumber *) identifier quantity:(NSInteger) quantity buyNow:(BOOL) buyNow callback:(void(^)(BOOL)) callback;
@end
@interface KWMSelectSizeVC : KWMBaseVC<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,KWMSizeDelegate>
......@@ -90,6 +92,6 @@
- (IBAction)onClickRemind:(id)sender;
- (IBAction)onClickFastBuy:(id)sender;
//- (IBAction)onClickFastBuy:(id)sender;
@end
......@@ -181,8 +181,12 @@
_shopCartModel.identifier = [NSString stringWithFormat:@"%@",_selectSize.identifier];
_shopCartModel.quantity = _count;
}
-(void)onClickComplete:(id)sender{
/**
* 点击加入购物车
*
* @param sender <#sender description#>
*/
-(void)onClickComplete:(UIButton *)sender{
if (self.selectSize == nil || self.count==0) {
[self showToast:@"请选择您想要的规格"];
return;
......@@ -191,58 +195,70 @@
[self showToast:@"该商品信息缺失"];
return;
}
KWMShopCartData *shopCartData = [[KWMShopCartData alloc] init];
if (_shopCartModel == nil) {
[self initModelByPrudct];
[self initBySelectSize];
[shopCartData inocreaseItem:_shopCartModel];
}else{
NSString *seletStr = [NSString stringWithFormat:@"%@",_selectSize.identifier];
_shopCartModel.quantity = _count;
//判断规格是否相同
if ([_shopCartModel.identifier isEqualToString:seletStr]) {
[self initBySelectSize];
[shopCartData changeNumberShopcart:_shopCartModel];
}else{
[shopCartData removeItem:_shopCartModel];
[self initBySelectSize];
//变为选择的规格
[shopCartData inocreaseItem:_shopCartModel];
}
}
self.btnComplete.userInteractionEnabled =NO;
if (_isShopcart) {
[self showToast:@"修改成功"];
}else{
[self showToast:@"加入成功"];
}
if (self.delegate != nil) {
[self.delegate kwm_addShopCartItem:_shopCartModel];
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:YES completion:nil];
});
}
//点击了快速购买按钮
-(void)onClickFastBuy:(id)sender{
if (self.selectSize == nil || self.count == 0) {
[self showToast:@"请选择您想要的规格"];
return;
}
if (self.product && !self.product.JSONDictionary){
[self showToast:@"该商品信息缺失"];
return;
}
BUYCart *cart = [self.client.modelManager insertCartWithJSONDictionary:nil];
[cart setVariant:self.selectSize withTotalQuantity:self.count];
[self dismissViewControllerAnimated:YES completion:nil];
if(self.delegate != nil){
[self.delegate kwm_fastBuy:cart];
BOOL buyNow = sender.tag == 1;
__weak id this = self;
[self showLoading];
if (self.delegate) {
[self.delegate kwm_addShopWithVariantId:_selectSize.identifier quantity:_count buyNow:buyNow callback:^(BOOL success) {
[self hideLoading];
if(success) {
[this dismissViewControllerAnimated:YES completion:nil];
}
}];
}
// KWMShopCartData *shopCartData = [[KWMShopCartData alloc] init];
// if (_shopCartModel == nil) {
// [self initModelByPrudct];
// [self initBySelectSize];
// [shopCartData inocreaseItem:_shopCartModel];
// }else{
// NSString *seletStr = [NSString stringWithFormat:@"%@",_selectSize.identifier];
// _shopCartModel.quantity = _count;
// //判断规格是否相同
// if ([_shopCartModel.identifier isEqualToString:seletStr]) {
// [self initBySelectSize];
// [shopCartData changeNumberShopcart:_shopCartModel];
// }else{
// [shopCartData removeItem:_shopCartModel];
// [self initBySelectSize];
// //变为选择的规格
// [shopCartData inocreaseItem:_shopCartModel];
// }
// }
// self.btnComplete.userInteractionEnabled =NO;
// if (_isShopcart) {
// [self showToast:@"修改成功"];
// }else{
// [self showToast:@"加入成功"];
// }
// if (self.delegate != nil) {
// [self.delegate kwm_addShopCartItem:_shopCartModel];
// }
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// [self dismissViewControllerAnimated:YES completion:nil];
// });
}
////点击了快速购买按钮
//-(void)onClickFastBuy:(id)sender{
//
// if (self.selectSize == nil || self.count == 0) {
// [self showToast:@"请选择您想要的规格"];
// return;
// }
// if (self.product && !self.product.JSONDictionary){
// [self showToast:@"该商品信息缺失"];
// return;
// }
// BUYCart *cart = [self.client.modelManager insertCartWithJSONDictionary:nil];
// [cart setVariant:self.selectSize withTotalQuantity:self.count];
// [self dismissViewControllerAnimated:YES completion:nil];
// if(self.delegate != nil){
// [self.delegate kwm_fastBuy:cart];
// }
//}
-(void)initData{
if(self.product == nil){
return;
......
......@@ -15,6 +15,7 @@
#import "KWMShopCartData.h"
#import "KWMNewVC.h"
#import "KWMStringUtil.h"
#import "KWMShoppingCart.h"
@interface KWMShopCartVC ()<KWMSelectSizeVCDelegate>
@property (nonatomic) NSMutableArray *shopCartList;
......@@ -22,6 +23,7 @@
@implementation KWMShopCartVC{
KWMShopCartModel *_removeModel;
KWMShopCartModel *_changeModel;
}
+(NSString *)kwmTag{
......@@ -37,7 +39,10 @@
// Do any additional setup after loading the view.
self.title = @"购物车";
// self.vBackground.hidden = NO;
_shopCartList = [NSMutableArray arrayWithArray:[[KWMShopCartData alloc] getALLItems]];
_shopCartList = (NSMutableArray *)[[KWMShoppingCart sharedInstance] items];
if (!_shopCartList) {
_shopCartList = [NSMutableArray arrayWithArray:[[KWMShopCartData alloc] getALLItems]];
}
if (_shopCartList.count == 0) {
self.vBackground.hidden = NO;
}else{
......@@ -47,6 +52,10 @@
self.btnRandom.layer.borderColor = [UIColor colorWithRed:78.0/255 green:78.0/255 blue:78.0/255 alpha:1.0].CGColor;
[self setTotalPrice];
__weak typeof(self) this = self;
[[KWMShoppingCart sharedInstance] allItemsWithCallback:^(NSError *error, KWMCartResult *cart) {
[this refresh];
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
......@@ -108,23 +117,36 @@
}
- (void)kwm_onClickEdit:(KWMShopCartModel *)shopCartModel{
self.definesPresentationContext = YES;
KWMSelectSizeVC *editVC = (KWMSelectSizeVC *)[KWMBaseVC findControllerBy:[KWMSelectSizeVC kwmTag] fromStoryboard:@"ShopCart"];
editVC.delegate = self;
BUYProduct * product = [[BUYProduct alloc] initWithModelManager:self.client.modelManager JSONDictionary:shopCartModel.shopCartDict];
editVC.isShopcart = YES;
editVC.product = product;
editVC.shopCartModel = shopCartModel;
//設置背景為透明
// if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
__block KWMShopCartVC *this = self;
_changeModel = shopCartModel;
[self showLoading];
[self.client getProductById:shopCartModel.product_id completion:^(BUYProduct * _Nullable product, NSError * _Nullable error) {
[this hideLoading];
this.definesPresentationContext = YES;
KWMSelectSizeVC *editVC = (KWMSelectSizeVC *)[KWMBaseVC findControllerBy:[KWMSelectSizeVC kwmTag] fromStoryboard:@"ShopCart"];
editVC.delegate = this;
// BUYProduct * product = [[BUYProduct alloc] initWithModelManager:self.client.modelManager JSONDictionary:shopCartModel.shopCartDict];
editVC.isShopcart = YES;
editVC.product = product;
editVC.shopCartModel = shopCartModel;
editVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
editVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
editVC.providesPresentationContextTransitionStyle = YES;
editVC.definesPresentationContext = YES;
[self presentViewController:editVC animated:YES completion:nil];
[this presentViewController:editVC animated:YES completion:nil];
}];
//設置背景為透明
// if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
// editVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
// editVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
// editVC.providesPresentationContextTransitionStyle = YES;
// editVC.definesPresentationContext = YES;
// [self presentViewController:editVC animated:YES completion:nil];
//下面這個方法在9.0的模擬器上嘗試發現失敗,8.0以下沒試過,不過官方模擬器都沒有8.0以下的可以下載了,也沒有支持的必要。
// }else{
......@@ -136,6 +158,29 @@
}
#pragma mark -- KWMSelectSizeVCDelegate
- (void)kwm_addShopWithVariantId:(NSNumber *)identifier quantity:(NSInteger)quantity buyNow:(BOOL)buyNow callback:(void (^)(BOOL))callback {
__weak KWMShopCartVC *this = self;
void(^success)(NSError*,KWMCartResult*) = ^(NSError *error,KWMCartResult *cart){
if (!error) {
[this refresh];
callback(YES);
}else{
[this showError:error];
callback(NO);
}
};
if (_changeModel.identifier.integerValue == identifier.integerValue) {
[[KWMShoppingCart sharedInstance] updateProductWithVariantId:identifier quantity:quantity callback:success];
}else{
NSNumber *oldId = @(_changeModel.identifier.integerValue);
_changeModel = nil;
[[KWMShoppingCart sharedInstance] deleteProductWithVariantId:oldId callback:^(NSError *error, KWMCartResult *cart) {
[[KWMShoppingCart sharedInstance] increaseProductWithVariantId:identifier quantity:quantity callback:success];
}];
}
}
- (void)kwm_addShopCartItem:(KWMShopCartModel *)shopCartModel{
[_shopCartList removeAllObjects];
......@@ -149,24 +194,37 @@
}
-(void)kwm_deleteProduct{
BOOL isHas = NO;
for (KWMShopCartModel *item in _shopCartList) {
if ([item isEqual:_removeModel]) {
isHas = YES;
break;
}
}
if (isHas) {
[_shopCartList removeObjectIdenticalTo:_removeModel];
}
// BOOL isHas = NO;
// for (KWMShopCartModel *item in _shopCartList) {
// if ([item isEqual:_removeModel]) {
// isHas = YES;
// break;
// }
// }
// if (isHas) {
// [_shopCartList removeObjectIdenticalTo:_removeModel];
// }
// [self.tbvCart reloadData];
// [self setTotalPrice];
// [[KWMShopCartData alloc] removeItem:_removeModel];
NSNumber *identifier = @(_removeModel.identifier.integerValue);
__weak KWMShopCartVC *this = self;
[self showLoading];
[[KWMShoppingCart sharedInstance] deleteProductWithVariantId:identifier callback:^(NSError *error, KWMCartResult *cart) {
[this hideLoading];
[this refresh];
}];
}
- (void)refresh {
self.shopCartList = [[KWMShoppingCart sharedInstance] items];
[self.tbvCart reloadData];
[self setTotalPrice];
[[KWMShopCartData alloc] removeItem:_removeModel];
}
//计算总价格
- (void) setTotalPrice{
float price = 0;
NSInteger price = 0;
for (KWMShopCartModel *model in _shopCartList) {
price += model.price * model.quantity;
}
......
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12118" systemVersion="16A323" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12120" systemVersion="16E195" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
<capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
......@@ -395,13 +395,13 @@
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="P10-ub-Wj1">
<rect key="frame" x="40" y="53" width="295" height="50"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="hBv-LJ-GxK">
<button opaque="NO" tag="1" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="hBv-LJ-GxK">
<rect key="frame" x="0.0" y="0.0" width="118" height="50"/>
<state key="normal" title="快速购买">
<color key="titleColor" red="0.22352941176470587" green="0.22352941176470587" blue="0.22352941176470587" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</state>
<connections>
<action selector="onClickFastBuy:" destination="22Z-pQ-E4P" eventType="touchUpInside" id="dH3-yW-rc8"/>
<action selector="onClickComplete:" destination="22Z-pQ-E4P" eventType="touchUpInside" id="hWG-fr-Qex"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="5wv-Z6-ZsU">
......
//
// UIViewController+AppearLog.h
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (AppearLog)
@end
//
// UIViewController+AppearLog.m
// iCemarose
//
// Created by lee on 2017/5/18.
// Copyright © 2017年 kollway. All rights reserved.
//
#import "UIViewController+AppearLog.h"
#import <JRSwizzle/JRSwizzle.h>
@implementation UIViewController (AppearLog)
+ (void)load
{
[self jr_swizzleMethod:@selector(viewWillAppear:) withMethod:@selector(logViewWillAppear:) error:nil];
}
- (void)logViewWillAppear:(BOOL) animated
{
NSLog(@"logViewWillAppear: %@",NSStringFromClass([self class]));
[self logViewWillAppear:animated];
}
@end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment