目錄
1、ATS配置
2淑翼、狀態(tài)欄全局變亮白
3腐巢、懶加載
4、內(nèi)存泄漏
5玄括、常用的第三方庫(kù)
6冯丙、反射機(jī)制
7、運(yùn)行時(shí)
8遭京、MD5加密
9胃惜、聊天界面
10、多線程GCD
11哪雕、 啟動(dòng)圖尺寸大小
12 船殉、權(quán)限
1、ATS配置
App 網(wǎng)絡(luò)http請(qǐng)求已被禁止斯嚎,需要在Info.plist文件配置利虫。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
2、狀態(tài)欄全局變亮白
UIApplication.shared.statusBarStyle = .lightContent
還需要在Info.plist文件配置:
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
3堡僻、懶加載
lazy var mainScrollView:UIScrollView = {()-> UIScrollView in
let scrollView = UIScrollView()
return scrollView
}()
4糠惫、內(nèi)存泄漏
解決閉包循環(huán)引用[weak self]
//ESPullToRefresh上拉加載
var footer: ESRefreshProtocol & ESRefreshAnimatorProtocol
footer = ESRefreshFooterAnimator.init(frame: CGRect.zero)
homeTableView.es.addInfiniteScrolling(animator: footer) { [weak self] in
self?.pageArray[tag]+=1
self?.initData(tag:tag+1,page:(self?.pageArray[tag]) ?? 1)
}
Timer釋放內(nèi)存
var timer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *) {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
print("定時(shí)器執(zhí)行")
})
} else {
timer=Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(write), userInfo: nil, repeats: true)
}
timer?.fire() //啟動(dòng)定時(shí)器
//timer?.fireDate=Date.distantFuture //暫停定時(shí)器
}
@objc func write(){
print("定時(shí)器執(zhí)行")
}
deinit{
timer?.invalidate()
timer=nil
print("銷毀定時(shí)器")
}
CADisplayLink釋放內(nèi)存
let displayLink = CADisplayLink.init(target: self, selector: #selector(write))
displayLink?.frameInterval = 1
displayLink?.add(to: .current, forMode: .commonModes)
//displayLink?.isPaused=false//暫停或開(kāi)始定時(shí)器
//銷毀定時(shí)器必須先執(zhí)行(deinit在這之后執(zhí)行)
displayLink?.invalidate()
//然后再執(zhí)行
displayLink=nil
WKWebView釋放內(nèi)存
//遵守WKScriptMessageHandler協(xié)議
webView = WKWebView.init(frame: self.view.bounds)
let request=URLRequest.init(url: URL.init(string: "http://www.reibang.com/u/665ff1bc9038")!)
webView?.load(request)
webView?.configuration.userContentController.add(self, name: "Delete")
self.view.addSubview(webView!)
//實(shí)現(xiàn)代理方法
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if "Delete" == message.name {
}
}
//銷毀WKWebView對(duì)象必須先執(zhí)行(deinit在這之后執(zhí)行)
webView?.configuration.userContentController.removeScriptMessageHandler(forName: "Delete")
//然后再執(zhí)行
webView=nil
NotificationCenter通知
//發(fā)送通知
let center = NotificationCenter.default
center.post(name: NSNotification.Name(rawValue: "Notification"), object: "傳單個(gè)值")
center.post(name: NSNotification.Name(rawValue: "Notification_More"), object: nil, userInfo: ["name":"星星編程","experience":"3年"])
//接收通知
var center = NotificationCenter.default
var observer:NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
center.addObserver(self, selector: #selector(receive), name: NSNotification.Name(rawValue: "Notification"), object: nil)
observer = center.addObserver(forName: NSNotification.Name(rawValue: "Notification_More"), object: nil, queue: OperationQueue.main) { (notification) in
print(notification.userInfo ?? "")
}
}
@objc func receive(notification:Notification){
print("接收到消息:" + "\(notification.object ?? "")")
}
deinit {
//center.removeObserver(self)//銷毀所以通知中心的監(jiān)聽(tīng)钉疫,不能銷毀NSObjectProtocol的監(jiān)聽(tīng)
center.removeObserver(self, name: NSNotification.Name(rawValue: "Notification"), object: nil)
// center.removeObserver(observer ?? self)//銷毀NSObjectProtocol的監(jiān)聽(tīng)
center.removeObserver(observer ?? self, name: NSNotification.Name(rawValue: "Notification_More"), object: nil)
print("移除通知監(jiān)聽(tīng)")
}
5硼讽、常用的第三方庫(kù)
網(wǎng)絡(luò)請(qǐng)求和生成Model的框架:AlamofireObjectMapper
首頁(yè)圖片輪播框架:GLLoopView
圖片加載框架:Kingfisher
上拉刷新下拉加載框架:ESPullToRefresh
6、反射機(jī)制
Mirror
class Book : NSObject {
var name:String? //書(shū)名
var author:String? //作者
var pages:Int? //頁(yè)數(shù)
}
let book = Book()
book.name = "簡(jiǎn)書(shū)"
book.author = "星星編程"
book.pages = 100
//是否是Book類的一個(gè)實(shí)例或?qū)嵗娜魏晤惱^承自Book類
if book.isKind(of: Book.classForCoder()){
print("book是Book的一個(gè)實(shí)例")
}
//是否是Book類的一個(gè)實(shí)例
if book.isMember(of: Book.classForCoder()) {
print("book是Book的一個(gè)實(shí)例")
}
//判斷self是否實(shí)現(xiàn)了aa方法
if self.responds(to: #selector(aa)){
print("aa")
}
//發(fā)送一個(gè)消息到指定消息的接收器,并返回結(jié)果
self.perform(#selector(aa))
//將對(duì)象進(jìn)行反射
let mirror = Mirror(reflecting: book)
print("對(duì)象類型:\(mirror.subjectType)")
print("對(duì)象子元素個(gè)數(shù):\(mirror.children.count)")
print("--- 對(duì)象子元素的屬性名和屬性值分別如下 ---")
for case let (key?, value) in mirror.children {
print("屬性:\(key) 值:\(value)")
}
NSClassFromString
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window?.backgroundColor = UIColor.white
//設(shè)置跟控制器要添加命名空間(默認(rèn)是項(xiàng)目名稱陌选,最好不要有特殊符號(hào))
let clsName = "StarsSwift.ViewController"
let cls = NSClassFromString(clsName) as? UIViewController.Type
//使用類來(lái)創(chuàng)建視圖控制器
let vc = cls?.init()
window?.rootViewController = vc
window?.makeKeyAndVisible()
return true
}
7理郑、運(yùn)行時(shí)
//通過(guò)KVC給對(duì)象賦值
let book = Book(dict: ["name" : "簡(jiǎn)書(shū)" , "author" : "星星編程" ,"introduction" : "假如編程欺騙了你蹄溉,你依舊義無(wú)反顧的熱愛(ài)編程,這才叫真愛(ài)您炉。" ])
print("書(shū)名:\(book.name ?? "") 作者:\(book.name ?? "") 簡(jiǎn)介:\(book.introduction ?? "")")
//打印通過(guò)運(yùn)行時(shí)獲取類的屬性
print(Book.propertyList())
//書(shū)類
class Book : NSObject{
@objc var name:String? //書(shū)名
@objc var author:String? //作者
@objc var introduction:String? //簡(jiǎn)介
init(dict:[String:Any]) {
super.init()
self.setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
class func propertyList()->[String]{
var count:UInt32=0
//獲取類的屬性列表柒爵,返回屬性列表數(shù)組
let list=class_copyPropertyList(self, &count)
var propertyList=[String]()
for i in 0..<Int(count){
guard let pty = list?[i]
else{
continue
}
let cName=property_getName(pty)
guard let name = String.init(utf8String: cName) else{
continue
}
propertyList.append(name)
}
free(list)
return propertyList
}
}
8、MD5加密
//
// String+MD5.swift
// StarsSwift
//
// Created by 李永飛 on 2017/10/26.
// Copyright ? 2017年 李永飛. All rights reserved.
//
import Foundation
extension String {
var md5: String {
if let data = self.data(using: .utf8, allowLossyConversion: true) {
let message = data.withUnsafeBytes { bytes -> [UInt8] in
return Array(UnsafeBufferPointer(start: bytes, count: data.count))
}
let MD5Calculator = MD5(message)
let MD5Data = MD5Calculator.calculate()
var MD5String = String()
for c in MD5Data {
MD5String += String(format: "%02x", c)
}
return MD5String
} else {
return self
}
}
}
9赚爵、聊天界面
10棉胀、多線程GCD
加載網(wǎng)絡(luò)數(shù)據(jù)及時(shí)更新UI
DispatchQueue.global().async {
//加載網(wǎng)絡(luò)數(shù)據(jù)
DispatchQueue.main.async(execute: {
//更新UI
})
}
延遲加載
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
//更新UI
})
DispatchGroup
let group = DispatchGroup()
let queueTask1 = DispatchQueue(label: "book")
queueTask1.async(group: group) {
print("任務(wù)1" )
}
let queueTask2 = DispatchQueue(label: "video")
queueTask2.async(group: group) {
print("任務(wù)2" )
}
group.notify(queue: DispatchQueue.main) {
print("任務(wù)完成" )
}
DispatchWorkItem
let queueTask = DispatchQueue(label: "queueTask", attributes: .concurrent)
let workItem1 = DispatchWorkItem {
print("WorkItem1")
}
let workItem2 = DispatchWorkItem {
print("WorkItem2")
}
queueTask.async(execute: workItem1)
queueTask.async(execute: workItem2)
DispatchGroup和DispatchWorkItem一起使用
let group = DispatchGroup()
let queueTask1 = DispatchQueue(label: "book")
queueTask1.async(group: group) {
print("任務(wù)1" )
}
let queueTask2 = DispatchQueue(label: "video")
queueTask2.async(group: group) {
print("任務(wù)2" )
}
let queueTask = DispatchQueue(label: "queueTask", attributes: .concurrent)
let workItem1 = DispatchWorkItem {
print("WorkItem1")
}
let workItem2 = DispatchWorkItem {
print("WorkItem2")
}
queueTask.async(group: group, execute: workItem1)
queueTask.async(group: group, execute: workItem2)
group.notify(queue: DispatchQueue.main) {
print("任務(wù)完成" )
}
11、 啟動(dòng)圖尺寸大小
iPhone Portrait iOS 11+ iPhone X (1125×2436) @3x
iPhone Portrait iOS 8,9-Retina HD 5.5 (1242×2208) @3x
iPhone Portrait iOS 8,9-Retina HD 4.7 (750×1334) @2x
iPhone Portrait iOS 7,8,9-2x (640×960) @2x
iPhone Portrait iOS 7,8,9-Retina 4 (640×1136) @2x
iPhone Portrait iOS 5,6-1x (320×480) @1x
iPhone Portrait iOS 5,6-2x (640×960) @2x
iPhone Portrait iOS 5,6-Retina4 (640×1136) @2x
12冀膝、 權(quán)限
通訊錄 NSContactsUsageDescription
麥克風(fēng) NSMicrophoneUsageDescription
相冊(cè) NSPhotoLibraryUsageDescription
相機(jī) NSCameraUsageDescription
添加圖片到相冊(cè) NSPhotoLibraryAddUsageDescription
持續(xù)獲取地理位置 NSLocationAlwaysUsageDescription
使用時(shí)獲取地理位置 NSLocationWhenInUseUsageDescription
藍(lán)牙 NSBluetoothPeripheralUsageDescription
語(yǔ)音轉(zhuǎn)文字 NSSpeechRecognitionUsageDescription
日歷 NSCalendarsUsageDescription