WTKit 1.2

WTKit 1.2

测试已测试
Lang语言 SwiftSwift
许可证 MIT
发布最后发布2018 年 3 月
SPM支持 SPM

mike 维护。



WTKit 1.2

  • 宋文通

WTKit

Build Status CocoaPods Compatible Carthage compatible Platform Gitter

WTKit 是我的代码积累

中文 Readme (Zh_cn)

功能

  • 便捷的请求/响应方法
  • 调试打印
  • 便捷的线程切换
  • 网络状态观察
  • 便捷的 UIColor 创建
  • UIButton 和 UIImageVie 图像下载、缓存
  • UITableView 拉刷新
  • UIView 截图图像
  • HudView
  • 构建的启动时间统计
  • 从 json 自动创建模型,模型实例自动从 json 数据设置值,自动写入 json
  • 更多

要求

  • iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.0+
  • Swift 3.0

安装

从 WTKit 复制源代码

通信

  • 如果您 发现了一个错误,请打开一个问题。
  • 如果您 有功能请求,请打开一个问题。
  • 如果您 想为此项目做出贡献,请提交一个 pull 请求。

CocoaPods

CocoaPods 是 Cocoa 项目的依赖管理器。您可以使用以下命令安装:

$ gem install cocoapods

要在您的 Xcode 项目中使用 CocoaPods 集成 WTKit,请在您的 Podfile 中指定它。

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target '<Your Target Name>' do
    pod 'WTKit', '~> 0.3.3'
end

然后,运行以下命令:

$ pod install

Carthage

Carthage 是一个去中心化的依赖管理器,它构建您的依赖并提供二进制框架。

您可以使用 Homebrew 安装 Carthage,命令如下:

$ brew update
$ brew install carthage

要在您的 Xcode 项目中使用 Carthage 集成 Alamofire,请在您的 Cartfile 中指定它。

github "swtlovewtt/WTKit" ~> 0.3.3

运行 carthage update 构建 Framework,并将构建好的 WTKit.framework 拖到 Xcode 项目中。

手动

从 WTKit 复制源代码

用法

JSON 模型

用于自动从JSON数据创建模型类,它们的实例可以从JSON数据自动更新属性

{
  "tz": 8,
  "area": "HK",
  "tz_name": "Asia/Hong_Kong",
  "id": "101819729",
  "current": {
    "current_version": "69e14038fd7bbe93ec5a259e36b48173"
  },
  "name": "Hong Kong",
  "province": "Hong Kong"
}
//WTKit can read json and parse to class like below,
//and the model class's instances can update json value to their properties
public class WeatherModel: NSObject,WTJSONModelProtocol {
    var tz:String?
    var area:String?
    var tz_name:String?
    var id:String?
    var name:String?
    var province:String?
    var current:CurrentModel?
    var day:DayModel?
    public func WTJSONModelClass(for property:String)->AnyObject?{
        if (property == "current") {
            return CurrentModel()
        }
        return nil
    }
}
public class CurrentModel: NSObject {
    var current_version:String?
    public func WTJSONModelClass(for property:String)->AnyObject?{
        return CurrentDetailModel()
    }
}

//auto update property from json data
weatherModel.wt(travel: jsonObject)

Note that the WTJSONModelProtocol protocol is implemented in the class that contains the custom properties so that the program knows what data is available at runtime

WTPrint

用于便于查看文件、方法、行号以及DEBUG模式下的输出

public func WTPrint<T>(_ items:T,
             separator: String = " ",
             terminator: String = "\n",
             file: String = #file,
             method: String = #function,
             line: Int = #line)

WTPrint("wt print \(self)")
//AppDelegate.swift[19], application(_:didFinishLaunchingWithOptions:) wt print <WTKit.AppDelegate: 0x7fde38509d80>

注意,Swift需要设置debug:构建设置 -> 其他Swift标志 -> Debug -> -D DEBUG

创建数据任务

import WTKit
let task = WTKit.dataTask(with: "https://www.apple.com") 
task.completionHandler = { [weak self](data, response, error) in
              print(response) //response
              print(data)     //data
              print(error)    //error
        }

WTKit中的网络操作是以异步方式进行的。对于不熟悉此概念的程序员来说,异步编程可能是一个令人沮丧的来源,但这样做有非常

完成处理

  • 数据响应
  • 字符串
  • JSON
  • UIImage

数据响应

let task = WTKit.dataTask(with: "https://www.apple.com") 
task.completionHandler = { [weak self](data, response, error) in
              print(response) //response
              print(data)     //data
              print(error)    //error
        }

字符串

task.stringHandler = {(string:String?,error:NSError?)in
            print(string)
        }

JSON

task.jsonHandler = {(object:AnyObject?,error:NSError?) in
            print(object)
        }

身份验证

身份验证在系统框架级别由URLCredentialURLAuthenticationChallenge处理。

支持的认证方案

高级使用

WTKit是建立在NSURLSession和Foundation URL加载系统之上的。为了充分利用此框架,建议您熟悉底层网络堆栈的概念和能力。

推荐阅读

App Transport Security (ATS)

随着iOS 9中App Transport Security (ATS)的引入,使用具有多个ServerTrustPolicy对象的自定义ServerTrustPolicyManager可能不起作用。如果您持续看到CFNetwork SSLHandshake failed (-9806)错误,您可能遇到了这个问题。Apple的ATS系统会覆盖整个挑战系统,除非您在应用程序的plist中配置ATS设置以禁用其中足够的部分,以便您的应用程序评估服务器信任。

如果您遇到这个问题(使用自签名证书的可能性很高),您可以通过向您的Info.plist中添加以下内容来解决这个问题。

<dict>
	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSExceptionDomains</key>
		<dict>
			<key>example.com</key>
			<dict>
				<key>NSExceptionAllowsInsecureHTTPLoads</key>
				<true/>
				<key>NSExceptionRequiresForwardSecrecy</key>
				<false/>
				<key>NSIncludesSubdomains</key>
				<true/>
				<!-- Optional: Specify minimum TLS version -->
				<key>NSTemporaryExceptionMinimumTLSVersion</key>
				<string>TLSv1.2</string>
			</dict>
		</dict>
	</dict>
</dict>

WebImage

如何使用

import WTKit
imageView.wt_setImage(with: imageURL, placeHolder: placeHolderImage)
  • 数据
//convert to string(utf-8)
public func toUTF8String()->String
//parse json
public func parseJson()->AnyObject?
  • OperationQueue
OperationQueue.main {
    let thread = Thread.current()
    print("main:\(thread) threadPriority:\(thread.threadPriority) qualityOfService:\(thread.qualityOfService.rawValue)")
}
OperationQueue.background {
    let thread = Thread.current()
    print("background:\(thread) threadPriority:\(thread.threadPriority) qualityOfService:\(thread.qualityOfService.rawValue)")

}
OperationQueue.userInteractive {
    let thread = Thread.current()
    print("userInteractive:\(thread) threadPriority:\(thread.threadPriority) qualityOfService:\(thread.qualityOfService.rawValue)")
}
OperationQueue.globalQueue {
    let thread = Thread.current()
    print("globalQueue:\(thread) threadPriority:\(thread.threadPriority) qualityOfService:\(thread.qualityOfService.rawValue)")
}

/*
//print
main:<NSThread: 0x7fbd40e04f40>{number = 1, name = main} threadPriority:0.758064516129032 qualityOfService:-1
globalQueue:<NSThread: 0x7fbd40c18b60>{number = 5, name = (null)} threadPriority:0.5 qualityOfService:-1
userInteractive:<NSThread: 0x7fbd40d10c10>{number = 3, name = (null)} threadPriority:0.5 qualityOfService:33
background:<NSThread: 0x7fbd40c7c540>{number = 4, name = (null)} threadPriority:0.0 qualityOfService:9

*/
  • 字符串
let string = "swift"
print(string.length)//5
  • 日期
// Get just one calendar unit value
 public func numberFor(component unit:Calendar.Unit)->Int{

date.numberFor(component: .year)
//2016

let date = Date()
print("year:\(date.numberForComponent(.year)) month:\(date.numberForComponent(.month)) day:\(date.numberForComponent(.day))")
//year:2016 month:6 day:15        
  • WTReachability

监控iOS设备的网络状态

var reachability:WTReachability = WTReachability.reachabilityWithHostName("www.apple.com")
reachability.startNotifier()
NotificationCenter.default().addObserver(forName: NSNotification.Name(rawValue: kWTReachabilityChangedNotification), object: nil, queue: nil) { [weak self](notification) in
            let reachability:WTReachability = notification.object as! WTReachability
            print(reachability.currentReachabilityStatus())
        }

UIKit 扩展

  • UIColor
UIColor.colorWithHexString("#3")//result is #333333
UIColor.colorWithHexString("333333")//result is #333333
UIColor.colorWithHexString("#333333")//result is #333333
UIColor.colorWithHexString("ff0000",alpha: 0.5)//red color with alpha : 0.5
  • UIApplication
//build version
UIApplication.buildVersion()
//app version
let appVersion:String = UIApplication.appVersion()
//documents path
let docPath:String = UIApplication.documentsPath()


//check if this launch is first launch,can use for everywhere,even use twice
UIApplication.firstLaunchForBuild { [weak self](isFirstLaunchEver) in
            if isFirstLaunchEver{
                print("this is first launch")
            }else{
                print("this is not first launch")
            }
        }

firstLaunchForBuild 这个方法在应用中多次使用效果相同,只需首次启动即可,无论是调用多少次,请放心使用

  • UIButton 请求图片然后缓存到本地
requestButton.setImageWith("url", forState: .Normal,placeHolder: nil)
  • UIImage

图片切成长方形

let image:UIImage = (self.imageView.image?.imageWithRoundCornerRadius(30))
  • UIImageView 请求图片,并本地缓存,下次设置图片时读取缓存
//set image with a url
imageView.setImageWith("url")

//set hight lighted image with a url,and set a place holder image
imageView.sethighlightedImageWith("url", placeHolder: placeHolderImage)
  • UIViewController 加载和提示
//hide loading
self.showLoadingView()

//hide loading
self.hideLoadingView()


//tip at bottom
self.showHudWithTip("热烈欢迎")
  • UIView UART 屏幕截图
let image:UIImage = self.view.snapShot()//get a snap shot image
let pdf:Data = self.view.pdf()//get a pdf shot
  • UIScrollView 向上拉刷新
//closure to refresh
self.tableView.refreshHeader = RefreshHeader.headerWithRefreshing({
            print("refresh data from internet")
        })

//stop Loading
self.tableView.stopLoading()

//local settings,default is English
tableView.refreshHeader?.setTitle("加载中...", forState: .Loading)
tableView.refreshHeader?.setTitle("下拉刷新", forState: .PullDownToRefresh)
tableView.refreshHeader?.setTitle("松开刷新", forState: .ReleaseToRefresh)
tableView.refreshHeader?.dateStyle = "yyyy-MM-dd"
tableView.refreshHeader?.lastUpdateText = "上次刷新时间"
//refresh image
tableView.refreshHeader?.arrowImageURL = "http://ww4.sinaimg.cn/mw690/47449485jw1f4wq45lqu6j201i02gq2p.jpg"
  • CALayer
let image:UIImage =  self.view.layer.snapShot()
//pause animation
self.view.layer.pauseAnimation()
//resume animation
self.view.layer.resumeAnimation()

许可

WTKit 基于 MIT 许可协议发布。详情请参阅 许可