GiftsView.swift
23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//
// GiftsView.swift
// WarplySDKFrameworkIOS
//
// Created by Manos Chorianopoulos on 18/4/22.
//
#if canImport(SwiftUI)
import SwiftUI
import Combine
import Foundation
import UIKit
class CouponSetItemModel {
let uuid: String?
let admin_name: String?
let name: String?
let img_preview: String?
let expiration: String?
let description: String?
let short_description: String?
let discount: String?
init(dictionary: [String: Any]) {
self.uuid = dictionary["uuid"] as? String? ?? ""
self.admin_name = dictionary["admin_name"] as? String? ?? ""
self.name = dictionary["name"] as? String? ?? ""
self.img_preview = dictionary["img_preview"] as? String? ?? ""
self.description = dictionary["description"] as? String? ?? ""
self.short_description = dictionary["short_description"] as? String? ?? ""
self.discount = dictionary["discount"] as? String? ?? ""
let expirationObject = dictionary["expiration"] as? [String: Any]? ?? ["":""]
let expirationString = expirationObject?["value"] as? String? ?? ""
// Example expirationString: Optional(2022-12-05 01:55)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm"
if let date = dateFormatter.date(from: expirationString ?? "") {
dateFormatter.dateFormat = "dd/MM/yyyy"
let resultString = dateFormatter.string(from: date)
self.expiration = resultString
} else {
self.expiration = ""
}
}
var asDictionary : [String:Any] {
let mirror = Mirror(reflecting: self)
let dict = Dictionary(uniqueKeysWithValues: mirror.children.lazy.map({ (label:String?, value:Any) -> (String, Any)? in
guard let label = label else { return nil }
return (label, value)
}).compactMap { $0 })
return dict
}
}
class CouponDataModel {
var data: Array<CouponSetItemModel> = []
init() { //initializer method
let instanceOfMyApi = MyApi()
let couponSets = instanceOfMyApi.getCouponSets(withActive: true, andVisible: true, andUuids: nil)
var couponSetsArray:Array<CouponSetItemModel> = []
if let myCouponsSetsDictionary = couponSets as? [String : AnyObject] {
let couponSetsData = (myCouponsSetsDictionary["MAPP_COUPON"] as! NSArray)
for couponset in couponSetsData {
let tempCouponset = CouponSetItemModel(dictionary: couponset as! [String : Any])
couponSetsArray.append(tempCouponset)
}
}
self.data = couponSetsArray
}
var getData: Array<CouponSetItemModel> {
get { // getter
return data
}
}
}
class CampaignItemModel {
let index_url: String?
let logo_url: String?
let offer_category: String?
let title: String?
let subtitle: String?
let session_uuid: String?
let subcategory: String?
init(dictionary: [String: Any]) {
self.index_url = dictionary["index_url"] as? String? ?? ""
self.logo_url = dictionary["logo_url"] as? String? ?? ""
self.offer_category = dictionary["offer_category"] as? String? ?? ""
self.title = dictionary["title"] as? String? ?? ""
self.subtitle = dictionary["subtitle"] as? String? ?? ""
self.session_uuid = dictionary["session_uuid"] as? String? ?? ""
// let extra_fields = dictionary["extra_fields"] as? [String: Any]? ?? ["":""]
let extra_fields = dictionary["extra_fields"] as AnyObject
var extra_fields_parsed:[String: Any]
let json = extra_fields.data(using: String.Encoding.utf8.rawValue)
do {
if let jsonArray = try JSONSerialization.jsonObject(with: json!, options: .allowFragments) as? [String:AnyObject]
{
extra_fields_parsed = jsonArray;
self.subcategory = extra_fields_parsed["subcategory"] as? String? ?? ""
} else {
self.subcategory = ""
print("bad json")
}
} catch let error as NSError {
self.subcategory = ""
print(error)
}
}
}
class CampaignDataModel {
var data: Array<CampaignItemModel> = []
init() { //initializer method
let instanceOfMyApi = MyApi()
let products = instanceOfMyApi.getInbox() as NSMutableArray?
var giftsArray:Array<CampaignItemModel> = []
for gift in products ?? [] {
let tempGift = CampaignItemModel(dictionary: gift as! [String : Any])
giftsArray.append(tempGift)
}
self.data = giftsArray;
}
var getData: Array<CampaignItemModel> {
get { // getter
return data
}
}
}
extension String {
func htmlToString() -> String {
return try! NSAttributedString(data: self.data(using: .utf8)!,
options: [.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil).string
}
}
extension View {
func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape( RoundedCorner(radius: radius, corners: corners) )
}
}
struct RoundedCorner: Shape {
var radius: CGFloat = .infinity
var corners: UIRectCorner = .allCorners
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}
class UrlImageModel: ObservableObject {
@Published var image: UIImage?
var urlString: String?
var imageCache = ImageCache.getImageCache()
func loadImage() {
if loadImageFromCache() {
print("Cache hit")
return
}
print("Cache miss, loading from url")
loadImageFromUrl()
}
func loadImageFromCache() -> Bool {
guard let urlString = urlString else {
return false
}
guard let cacheImage = imageCache.get(forKey: urlString) else {
return false
}
image = cacheImage
return true
}
func loadImageFromUrl() {
guard let urlString = urlString else {
return
}
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url, completionHandler: getImageFromResponse(data:response:error:))
task.resume()
}
func getImageFromResponse(data: Data?, response: URLResponse?, error: Error?) {
guard error == nil else {
print("Error: \(error!)")
return
}
guard let data = data else {
print("No data found")
return
}
DispatchQueue.main.async {
guard let loadedImage = UIImage(data: data) else {
return
}
self.imageCache.set(forKey: self.urlString!, image: loadedImage)
self.image = loadedImage
}
}
init(urlString:String) {
self.urlString = urlString
loadImage()
}
}
class ImageCache {
var cache = NSCache<NSString, UIImage>()
func get(forKey: String) -> UIImage? {
return cache.object(forKey: NSString(string: forKey))
}
func set(forKey: String, image: UIImage) {
cache.setObject(image, forKey: NSString(string: forKey))
}
}
extension ImageCache {
private static var imageCache = ImageCache()
static func getImageCache() -> ImageCache {
return imageCache
}
}
extension GiftsView {
struct headerView: View {
var goBack: () -> ()
var uiscreen = UIScreen.main.bounds
var body: some View {
HStack(alignment: .center) {
Button {
// Button Action
print("Back Button tapped!")
goBack()
} label: {
Image("ic_back", bundle: Bundle(for: MyEmptyClass.self))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: self.uiscreen.height * 0.025, height: self.uiscreen.height * 0.02)
}
Text("Gifts for You")
.fontWeight(.medium)
.font(.system(size: 16))
.foregroundColor(Color(red: 0.20784313725490197, green: 0.3176470588235294, blue: 0.40784313725490196))
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.padding(.horizontal)
Button {
// Button Action
print("Location tapped!")
} label: {
Image("location_icon", bundle: Bundle(for: MyEmptyClass.self))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: self.uiscreen.height * 0.04, height: self.uiscreen.height * 0.04)
}
}
.frame(maxWidth: .infinity)
.padding(.horizontal)
.padding(.vertical, 10)
}
}
struct searchView: View {
@State var searchText: String = ""
var uiscreen = UIScreen.main.bounds
var body: some View {
HStack(alignment: .center) {
HStack(alignment: .center) {
Image("search_icon", bundle: Bundle(for: MyEmptyClass.self))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: self.uiscreen.height * 0.025, height: self.uiscreen.height * 0.025)
.padding([.top, .leading, .bottom], 10)
TextField("Βρες το gift που σε ενδιαφέρει", text: $searchText)
.frame(maxWidth: .infinity)
.padding(.all, 10)
.foregroundColor(Color(red: 0.48627450980392156, green: 0.48627450980392156, blue: 0.48627450980392156))
.font(.system(size: 16, weight: .regular, design: .default))
}
.overlay(
RoundedRectangle(cornerRadius: 9)
.stroke(Color(red: 0.8235294117647058, green: 0.8235294117647058, blue: 0.8235294117647058), lineWidth: 1)
)
Button {
// Button Action
print("Filters tapped!")
} label: {
Image("filters_btn", bundle: Bundle(for: MyEmptyClass.self))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: self.uiscreen.height * 0.06, height: self.uiscreen.height * 0.04)
.padding(.leading, 5)
}
}
.frame(maxWidth: .infinity)
.padding(.horizontal, 20)
.padding(.vertical, 5)
}
}
struct ImageView: View {
@ObservedObject var imageLoader:UrlImageModel
@State var width:CGFloat
@State var isFill:Bool
var uiscreen = UIScreen.main.bounds
init(withURL url:String , width:CGFloat, isFill:Bool) {
imageLoader = UrlImageModel(urlString:url)
self.width = width
self.isFill = isFill
}
var body: some View {
Image(uiImage: imageLoader.image ?? UIImage())
.resizable()
.aspectRatio(contentMode: isFill ? .fill : .fit)
.frame(width: self.width)
.frame(maxHeight: .infinity)
}
}
struct giftItemView: View {
var item: CampaignItemModel
var isFirst: Bool
var isLast: Bool
var parentView: UIView
var uiscreen = UIScreen.main.bounds
var body: some View {
Button {
// GiftItem Action
let instanceOfMyApi = MyApi()
let campaignViewController = instanceOfMyApi.openCampaign(parentView, campaign: item.index_url)!
campaignViewController.view.tag = 6
// addChild(couponsViewController)
campaignViewController.view.frame = parentView.frame
parentView.addSubview(campaignViewController.view)
campaignViewController.didMove(toParent: UIHostingController(rootView: self))
} label: {
HStack(alignment: .center) {
ImageView(withURL: item.logo_url ?? "", width: self.uiscreen.width * 0.5, isFill: true)
Text(item.title ?? "")
.fontWeight(.regular)
.font(.system(size: 16))
.foregroundColor(Color(red: 0.22745098039215686, green: 0.3215686274509804, blue: 0.4))
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.all, 10)
.background(Color.white)
}
}
.frame(width: self.uiscreen.width * 0.9, height: self.uiscreen.height * 0.16)
.background(Color.white)
.cornerRadius(5)
.shadow(color: Color(red: 0, green: 0, blue: 0, opacity: 0.16), radius: 30, x: 0, y: 3)
.padding(.leading, isFirst ? 18 : 0)
.padding(.trailing, isLast ? 18 : 0)
}
}
struct giftsContainer: View {
@State var gifts:Array<CampaignItemModel> = []
@State var title:String = ""
@State var parentView:UIView
var uiscreen = UIScreen.main.bounds
var body: some View {
VStack(alignment: .leading) {
Text(title)
.fontWeight(.bold)
.font(.system(size: 17))
.foregroundColor(Color.white)
.multilineTextAlignment(.leading)
.padding(.horizontal)
.padding(.top, self.uiscreen.height * 0.05)
.padding(.bottom, self.uiscreen.height * 0.015)
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center) {
ForEach(Array(gifts.enumerated()), id: \.offset) { index, item in
giftItemView(item: item, isFirst: index == 0, isLast: index == (gifts.count-1), parentView: parentView)
}
}
.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity)
}
}
struct couponsContainer: View {
@State var coupons:Array<CouponSetItemModel> = []
@State var title:String = ""
@State var parentView:UIView
var uiscreen = UIScreen.main.bounds
var body: some View {
VStack(alignment: .leading) {
Text(title)
.fontWeight(.bold)
.font(.system(size: 17))
.foregroundColor(Color.white)
.multilineTextAlignment(.leading)
.padding(.horizontal)
.padding(.top, self.uiscreen.height * 0.05)
.padding(.bottom, self.uiscreen.height * 0.015)
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center) {
ForEach(Array(coupons.enumerated()), id: \.offset) { index, item in
couponItemView(item: item, isFirst: index == 0, isLast: index == (coupons.count-1), parentView: parentView)
}
}
.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity)
.padding(.bottom, self.uiscreen.height * 0.1)
}
}
struct couponItemView: View {
var item: CouponSetItemModel
var isFirst: Bool
var isLast: Bool
var parentView: UIView
var uiscreen = UIScreen.main.bounds
var body: some View {
Button {
// GiftItem Action
let tempItem = item.asDictionary
let instanceOfMyApi = MyApi()
let couponViewController = instanceOfMyApi.openCoupon(parentView, coupon: tempItem)!
couponViewController.view.tag = 2
// addChild(couponsViewController)
couponViewController.view.frame = parentView.frame
parentView.addSubview(couponViewController.view)
couponViewController.didMove(toParent: UIHostingController(rootView: self))
} label: {
HStack(alignment: .center) {
ImageView(withURL: item.img_preview ?? "", width: self.uiscreen.width * 0.15, isFill: false)
VLine()
.stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
.foregroundColor(Color(red: 0.4392156862745098, green: 0.4392156862745098, blue: 0.4392156862745098))
.frame(width: 1)
.padding(.leading, 10)
VStack(alignment: .leading) {
Text(item.name ?? "")
.fontWeight(.medium)
.font(.system(size: 16))
.foregroundColor(Color(red: 0.22745098039215686, green: 0.3215686274509804, blue: 0.4))
.multilineTextAlignment(.leading)
.lineLimit(1)
// .frame(maxWidth: .infinity)
HStack(alignment: .center) {
Text((item.discount ?? "")+"€")
.fontWeight(.bold)
.font(.system(size: 25))
.foregroundColor(Color(red: 0.22745098039215686, green: 0.3215686274509804, blue: 0.4))
.multilineTextAlignment(.leading)
.lineLimit(1)
// .frame(width: self.uiscreen.width * 0.3)
// .frame(maxWidth: .infinity, maxHeight: .infinity)
Text(item.short_description ?? "")
.fontWeight(.medium)
.font(.system(size: 11))
.foregroundColor(Color(red: 0.3803921568627451, green: 0.44313725490196076, blue: 0.5058823529411764))
.multilineTextAlignment(.leading)
.lineLimit(3)
// .frame(maxWidth: .infinity)
// .padding(.leading, 10)
}
// .padding(.vertical, 5)
.frame(maxHeight: .infinity)
Text("Ισχύει έως "+(item.expiration ?? ""))
.fontWeight(.medium)
.font(.system(size: 11))
.foregroundColor(Color(red: 0.3803921568627451, green: 0.44313725490196076, blue: 0.5058823529411764))
.multilineTextAlignment(.leading)
// .frame(maxWidth: .infinity)
// .frame(maxWidth: .infinity, maxHeight: .infinity)
// .padding(.all, 10)
}
.padding(.all, 10)
// .frame(maxWidth: .infinity, maxHeight: .infinity)
Spacer()
}
.padding(.leading, 28)
.padding(.trailing)
}
.frame(width: self.uiscreen.width * 0.9, height: self.uiscreen.height * 0.14)
.cornerRadius(5)
.shadow(color: Color(red: 0, green: 0, blue: 0, opacity: 0.16), radius: 30, x: 0, y: 3)
.padding(.leading, isFirst ? 18 : 0)
.padding(.trailing, isLast ? 18 : 0)
.background(
Image("coupon_bg", bundle: Bundle(for: MyEmptyClass.self))
.resizable(resizingMode: .stretch)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.leading, isFirst ? 18 : 0)
.padding(.trailing, isLast ? 18 : 0)
)
}
}
struct VLine: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
}
}
}
}
@available(iOS 13.0.0, *)
struct GiftsView: View {
var parentView: UIView
var coupons:Array<CouponSetItemModel> = CouponDataModel().getData
var campains:Array<CampaignItemModel> = CampaignDataModel().getData.filter { $0.offer_category == "gifts_for_you" }
var uiscreen = UIScreen.main.bounds
func goBack(){
for subview in parentView.subviews {
if(subview.tag == 5) {
subview.removeFromSuperview()
}
}
}
var body: some View {
VStack {
headerView(goBack: goBack)
searchView()
ScrollView(showsIndicators: false) {
VStack {
if (campains.filter { $0.subcategory == "gifts" }.count) > 0 {
giftsContainer(gifts: campains.filter { $0.subcategory == "gifts" }, title: "ΔΩΡΑ", parentView: parentView)
}
if (campains.filter { $0.subcategory == "rewards" }.count) > 0 {
giftsContainer(gifts: campains.filter { $0.subcategory == "rewards"}, title: "ΕΠΙΒΡΑΒΕΥΣΕΙΣ", parentView: parentView )
}
if (coupons.count) > 0 {
couponsContainer(coupons: coupons, title: "ΚΟΥΠΟΝΙΑ", parentView: parentView )
}
}
.frame(width:self.uiscreen.width)
}
.background(
LinearGradient(gradient: Gradient(colors: [Color(red: 0.06, green: 0.67, blue: 0.84), Color(red: 0.47, green: 0.75, blue: 0.43)]), startPoint: .top, endPoint: .bottom)
)
.cornerRadius(30, corners: [.topLeft])
.frame(width:self.uiscreen.width)
.frame(maxHeight: .infinity)
}
.edgesIgnoringSafeArea([.bottom])
.frame(width:self.uiscreen.width)
.frame(maxHeight: .infinity)
}
}
#endif
//@available(iOS 13.0.0, *)
//struct GiftsView_Previews: PreviewProvider {
// static var previews: some View {
//
// GiftsView()
//
// }
//}