项目作者: songwentong

项目描述 :
Swift extensions
高级语言: Swift
项目地址: git://github.com/songwentong/WTKit.git
创建时间: 2016-06-12T03:18:44Z
项目社区:https://github.com/songwentong/WTKit

开源协议:MIT License

下载




Swift
Platform
Swift Package Manager

WTKit

中文请看这里
WTKit is my swift accumulated experience,I think WTKit could help you to improve development efficiency.

Features

  • Codable extensions(JSON Decode with type-Adaption)
  • cURL Command Output
  • Making Codable Requests
  • Simulation response data for test
  • Load Web Image
  • String to UIColor
  • Table Model
  • WTGradientView
  • Base Hud View(text/indicator)
  • Version track

Codable extensions(JSON Decode/enode, model creater)

WTKit can create a swift model file from json

type-Adaption decode json,WTKit resove JSONDecoder type mismatch error,and convert is to the type you need,like Int can decode from String/Double/Int, or String can decode from String/Double/Int

Endocable/Decodable extensions,Decodable can decode from JSON,Encodable can map to json string

  1. func json1() -> String {
  2. let json1 = """
  3. {
  4. "intValue": 3,
  5. "strValue": "3.8",
  6. "double": "3.5",
  7. "intList": [
  8. 1,
  9. 2
  10. ],
  11. "flag": true,
  12. "doubleList": [
  13. 1.1,
  14. 2.2
  15. ],
  16. "object": {
  17. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  18. "Accept-Encoding": "gzip, deflate, br",
  19. "Accept-Language": "zh-cn",
  20. "Host": "httpbin.org",
  21. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15",
  22. "X-Amzn-Trace-Id": "Root=1-5e716637-2f2252cc4747e55326ef4a08"
  23. },
  24. "objectList": [
  25. {
  26. "id": 145,
  27. "title": "喜欢你",
  28. "num": "4",
  29. "pic": "https://img3.tuwandata.com/uploads/play/9766281560847422.png"
  30. },
  31. {
  32. "id": 148,
  33. "title": "么么哒",
  34. "num": "3",
  35. "pic": "https://img3.tuwandata.com/uploads/play/6851431563789324.png"
  36. }
  37. ]
  38. }
  39. """
  40. return json1
  41. }
  42. ///Codable模型创建
  43. ///给出一个class/struct名和json字符串,创建一个对应名字的class/struct
  44. ///并写入Document目录
  45. ///model处理了类型异常并转化,
  46. ///Int类型如果收到了String会自动转化类型,反之亦然
  47. ///对象类型和其他复杂类型也做了异常处理,不再抛出异常
  48. func testModelCreate() {
  49. let maker = WTModelMaker.default
  50. // maker.needOptionalMark = false
  51. // maker.useStruct = true
  52. let className = "TestModel"
  53. let classCode = maker.createModelWith(className: className, jsonString: json1())
  54. print(NSHomeDirectory())
  55. // print(classCode)
  56. let path = NSHomeDirectory() + "/Documents/" + className + ".swift"
  57. print(path)
  58. do {
  59. try classCode.write(toFile: path, atomically: true, encoding: .utf8)
  60. #if os(macOS)
  61. let url = path.urlValue
  62. NSWorkspace.shared.activateFileViewerSelecting([url])
  63. NSWorkspace.shared.selectFile(path, inFileViewerRootedAtPath: "/")
  64. #else
  65. #endif
  66. } catch {
  67. }
  68. }
  69. /**
  70. test model Decode 测试数据解码
  71. contains type error/key not found 包含了类型异常,字段异常
  72. Int/Double/String type error handle and transfer to type 异常处理
  73. others decode no error throws
  74. */
  75. func testDecode() {
  76. guard let obj2 = TestModel.decodeIfPresent(with: json1().utf8Data) else{
  77. return
  78. }
  79. print(obj2.jsonString)
  80. }

Making Codable Requests

WTKit provides a variety of convenience methods for making HTTP requests.

  1. public extension URLSession{
  2. ///this method can make a urlrequest and convert result to Codable instance
  3. func dataTaskWith<T:Codable>( request:URLRequest, testData:Data? = nil, codable object:@escaping (T)->Void,completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask{}
  4. }
  5. public class HttpBin:NSObject, Codable {
  6. var url:String = ""
  7. var origin:String = ""
  8. enum CodingKeys: String, CodingKey {
  9. case url = "url"
  10. case origin = "origin"
  11. }
  12. }
  13. let request = "https://httpbin.org/get".urlRequest
  14. let task = WT.dataTaskWith(request:request,
  15. codable: { (model:HttpBin) in
  16. //model is parsed Codable instance
  17. print("\(model)")
  18. }) { (data, res, err) in
  19. }
  20. task.resume()

Simulation response data

this feature is only effect on DEBUG

  1. //Simulation data
  2. let simData =
  3. """
  4. {
  5. "args": {},
  6. "headers": {
  7. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  8. "Accept-Encoding": "gzip, deflate, br",
  9. "Accept-Language": "zh-cn",
  10. "Host": "httpbin.org",
  11. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15",
  12. "X-Amzn-Trace-Id": "Root=1-5e716637-2f2252cc4747e55326ef4a08"
  13. },
  14. "origin": "123.112.227.96",
  15. "url": "https://httpbin.org/get"
  16. }
  17. """
  18. let req = "https://httpbin.org".urlRequest
  19. //if in DEBUG Mode,and testData != nil
  20. //the simulatedData will take effect
  21. WT.dataTaskWith(request: req, testData: simData,
  22. codable: { (obj:HttpBin) in
  23. //in debug mode ,obj will parse from testData if not nil
  24. }) { (data, res, err) in
  25. }

cURL Command Output

Debug tool

  1. let request = "https://httpbin.org/get".urlRequest
  2. print(request.printer)

or you can print it in lldb:

  1. (lldb) po request.printer

This should produce:

  1. $ curl -v \
  2. -X GET \
  3. -H "Accept-Language: en;q=1.0" \
  4. -H "Accept-Encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8" \
  5. -H "User-Agent: Demo/1.0 (com.demo.Demo; build:1; iOS 13.0.0) WTKit/1.0" \
  6. "https://httpbin.org/get"

WTModelMaker

WTModelMaker can create Codable model class/struct File from JSON Data
https://github.com/songwentong/ModelMaker
additional Xcode App on Mac,using it to create Codable file Convenience,just copy your json ,edit class name,and press ‘Write file’,your file will create easily.
and it will over write description and debugDescription automatic. this feature is very useful,swift default won’t print properties for you(just like Model:<0x00000f1231>),if you print obj it will show you,if you want to see property values,just print it at lldb or print it.
model using CodkingKeys by default,you can rename map easily.

without description/debugDescription

with description/debugDescription

  1. print(obj)
  2. //or
  3. (lldb) po obj
  4. /**
  5. //output will be
  6. args:debugDescription of args_class:
  7. url:https://httpbin.org/get
  8. headers:debugDescription of headers_class:
  9. Accept:text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8
  10. Host:httpbin.org
  11. User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15
  12. Accept-Language:zh-cn
  13. Accept-Encoding:gzip, deflate, br
  14. X-Amzn-Trace-Id:Root=1-5e6b977f-43ebdc40121912f0bb6dc3d0
  15. origin:123.120.230.73
  16. */

Encodable extension

create json data from encodable objec

  1. let obj:Encodable
  2. print(obj.jsonString)
  3. //or
  4. (lldb) po obj.lldbPrint()
  5. //output will be json like this
  6. {
  7. "args": {},
  8. "origin": "123.120.230.73",
  9. "url": "https://httpbin.org/get"
  10. }

String hex color

  1. "f".hexColor //white UIColor,it same as "ffffff"
  2. "#3".hexColor //same as 333333
  3. "ff0000".hexColor//red UIColor
  4. "ff0000".hexCGColor//red CGColor

more:

WTGradientView

An UIView hold CAGradientView edit it’s property will take effect on it’s layer.

  1. let gview = WTGradientView()
  2. gview.colors = ["f".hexCGColor, "990000".hexCGColor]
  3. gview.locations = [0, 1]
  4. gview.startPoint = CGPoint(x: 0, y: 0.5)
  5. gview.endPoint = CGPoint(x: 1, y: 0.5)
  6. //it will effect on it's CAGradientView automatic

UIView extension

  1. //Cell reuse id,like it's class name
  2. let reuseID:String = Cell.reuseIdentifier
  3. print("\(reuseID)")
  4. //Cell
  5. //auto load it's nib file(if class name equal to xib file)
  6. let nib:UINib = Cell.nib()
  7. //you can use this nib and reuseId to regist/dequeue use the cell

HUD View

  1. ///normal tip
  2. view.showTextTip(text:"tip")
  3. ///debug tip,show only in debug mode
  4. view.debugTip(text:"tip")

effect:

Version Track

feature to log build history

  1. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  2. application.track()//track twice no effect
  3. application.versionHistory()//version history
  4. application.buildHistory()//build history
  5. application.isFirstLaunchForBuild//check is first build
  6. }

WT Table Model

The abstract strategy for object-oriented development is used here, which is also the embodiment of the Model part in the MVC pattern.using Protocol oriented programming to describe UITableView as a Model,this will be more flexible,no class tree’s constraint.

  1. //cell model
  2. public protocol UITableViewCellModel{
  3. var reuseIdentifier: String{get set}
  4. var object: Any?{get set}
  5. var userInfo: [AnyHashable : Any]?{get set}
  6. }
  7. //section model
  8. public protocol UITableViewSectionModel {
  9. var cells:[UITableViewCellModel]{get set}
  10. }
  11. //table model
  12. public protocol UITableViewModel {
  13. var sections:[UITableViewSectionModel]{get set}
  14. }

more

  1. //you can use this protocol to describe some Cells more info
  2. public protocol UITableViewCellDetailModel:UITableViewCellModel {
  3. var height:CGFloat{get set}
  4. var didSelectAction:DispatchWorkItem?{get set}
  5. var willDisplayAction:DispatchWorkItem?{get set}
  6. var prefetchAction:DispatchWorkItem?{get set}
  7. var cancelPrefetchingAction:DispatchWorkItem?{get set}
  8. }

send data.

these methods is suitable for all case using WTTableModel.

  1. public protocol UITableViewCellModelHolder {
  2. var model:UITableViewCellModel?{get set}
  3. }
  4. public extension UITableView{
  5. func dequeueReusableCellModel(withModel model:UITableViewCellModel, for indexPath: IndexPath) -> UITableViewCell {
  6. let cell = dequeueReusableCell(withIdentifier: model.reuseIdentifier, for: indexPath)
  7. if var c = cell as? UITableViewCellModelHolder{
  8. c.model = model
  9. }
  10. return cell
  11. }
  12. }

UIView + Xib

create UIView(or subclass) from nib,when you may want to reuse UIView in xib file, you can use it, I suggest you use UITableViewCell instead of UIVIew,because it has a contentVie w, no file’s owner issue.

  1. let myView:MyView = MyView.instanceFromXib()
  2. //create MyView instance from xib file
  3. //usually use it as UITableViewCell sub class to avoid file owner issue

UIViewController + IB

create UIViewController instance from storyboard/nib

  1. let vc:CustromVC = CustromVC.instanceFromStoryBoard()
  2. //this func is create instance from you Storyboard's root VC
  3. let vc2:CustromVC = CustromVC.instanceFromNib()
  4. //create instance from nib file

Local Manager

edit customBundle of Bundle can change local language easily

  1. //using english
  2. Bundle.customBundle = enUS
  3. print("language".customLocalizedString)
  4. //output will be
  5. //language
  6. print("english".customLocalizedString)
  7. //english
  8. Bundle.customBundle = zhCN
  9. print("language".customLocalizedString)
  10. //output will be
  11. //语言
  12. print("english".customLocalizedString)
  13. //英语

Installation

swift package manager

From Xcode 11, you can use Swift Package Manager to add WTKit to your project.

  • Select File > Swift Packages > Add Package Dependency. Enter https://github.com/songwentong/WTKit.git in the “Choose Package Repository” dialog.
  • In the next page, specify the rule as master branch
  • After Xcode checking out the source and resolving the version, you can choose the “WTKit” library and add it to your app target.
    1. https://github.com/songwentong/WTKit.git
    or
    1. .package(url: "https://github.com/songwentong/WTKit.git", branch: "master"),