本文主要記錄swift中delegate的使用、“?!”Optional的概念、GCD的使用、request請求、網路載入圖片並儲存到沙箱、閉包以及橋接。
一、delegate的使用
swift中delegate的使用和objective-c大同小異,簡單記錄一下:
step1:宣告
@objc protocol testProtocol:NSObjectProtocol{
@objc optional func testAdd( a:Int, b:Int) -> Int;
}
step2:例項化
class TextFieldViewController: UIViewController ,UITextFieldDelegate{
var delegate:testProtocol!
}
step3:呼叫delegate響應(此處沒有處理delegate為空的情況,因為使用了“?”,當delegate為nil的時候,後面的testAdd不會被執行)
// if (self.delegate != nil)&&(self.delegate?.responds(to:#selector(testProtocol.testAdd(a:b:))))!{
// let result = self.delegate!.testAdd!(a: 2, b: 5)
// print(result)
// }
let result = self.delegate?.testAdd!(a: 3, b: 1)
print(result ?? "delegate沒有響應")
step4:其他類遵循並實現協議
class UIBaseViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,testProtocol{
func testAdd( a:Int, b:Int) -> Int{
print(a+b)
return a+b
}
func jump{
let txtVC = TextFieldViewController()
txtVC.delegate = self
self.navigationController?.pushViewController(txtVC, animated: true)
}
}
二、“? !”的使用和含義
詳細深層的理解,請Google,百度,下面簡單記錄使用時的區別
self.navigationController?.pushViewController(txtVC, animated: true)
上面的“?”處理邏輯是,當navigationController為nil時直接不執行後面的push操作,當navigationController存在時執行後面的push操作。
self.navigationController!.pushViewController(txtVC, animated: true)
上面的“!”對UINavigationController?進行了手動解包,也就是說navigationController絕對存在,否則(navigationController為nil)程式就會直接崩潰。
三、GCD使用
1、同步
func dispatch_sync(){
let queue = DispatchQueue(label: "com.test.queuesync")
queue.sync {
for i in 0...10{
print("sync test --- ",i)
}
print(" ---同步執行結束 子執行緒---")
}
}
2、非同步
func dispatch_async(){
let queue = DispatchQueue(label: "com.test.queueasync")
queue.async {
for i in 0...10{
print("async test --- ",i)
}
print(" ---非同步執行結束 子執行緒---")
}
}
3、延時
func dispatch_delay(){
let queue = DispatchQueue(label: "com.test.queuedelay")
queue.asyncAfter(deadline: DispatchTime.now()+DispatchTimeInterval.seconds(3), execute: {
print(" ---延遲執行執行結束 子執行緒---")
})
}
4、回到主執行緒
func dispatch_main(){
let queue = DispatchQueue(label: "com.test.backtomain")
queue.async{
DispatchQueue.main.sync {
print(" ---回到主執行緒---")
}
}
}
5、全域性併發佇列
func dispatch_global(){
let queue = DispatchQueue.global()
let workItem = DispatchWorkItem{
print("呼叫了workitem")
}
queue.async {
for i in 0...10{
print("async test --- ",i)
}
workItem.perform();
print(" ---global非同步執行結束 子執行緒---")
}
}
四、request
1、GET請求
func getRequest(){
let url = URL.init(string: "https://api.github.com/repos/alibaba/weex")
let request = NSMutableURLRequest.init(url:url!)
request.httpMethod = "GET"
request.timeoutInterval = 10
// let params = "type=shentong&postid=3333557693903" as NSString
// request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// request.httpBody = params.data(using: String.Encoding.utf8.rawValue)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if (error != nil) {
print(error ?? "")
return
}else {
//此處是具體的解析,具體請移步下面
do{
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
// let json: Any = try! JSONSerialization.jsonObject(with: data!, options: [])
// print(json)
JYToast.showInMidWindow(title: NSString.init(format: "data is -- \n %@", json as! CVarArg) as String)
}catch{
print(error.localizedDescription)
}
}
}
dataTask.resume()
}
2、POST請求
func postRequest(){
let url = URL.init(string: "http://www.kuaidi100.com/query")
let request = NSMutableURLRequest.init(url:url!)
request.httpMethod = "POST"
request.timeoutInterval = 10
let params = "type=shentong&postid=3333557693903" as NSString
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = params.data(using: String.Encoding.utf8.rawValue)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if (error != nil) {
print(error ?? "")
JYToast.showInMidWindow(title: NSString.init(format: "error is -- \n %@", error! as CVarArg) as String)
return
}else {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
JYToast.showInMidWindow(title: NSString.init(format: "data is -- \n %@", json as! CVarArg) as String)
}catch{
print(error.localizedDescription)
}
}
}
dataTask.resume()
}
五、載入網路圖片並儲存到沙箱
let queue = DispatchQueue.global();
queue.async {
let data = NSData.init(contentsOf: NSURL.init(string: "http://c.hiphotos.baidu.com/image/h%3D300/sign=58adc7aa3c2ac65c78056073cbf3b21d/3b292df5e0fe9925de1b729a3da85edf8cb171e0.jpg")! as URL)
let image = UIImage.init(data: data! as Data)
let doc = NSHomeDirectory() as NSString
doc.appendingPathComponent("Documents/1.jpg")
do{
try data?.write(toFile: doc.appendingPathComponent("Documents/1.jpg"), options: NSData.WritingOptions.atomic)
}catch{
print(error.localizedDescription)
}
let main = DispatchQueue.main
main.async {
let imageView = UIImageView.init(frame: CGRect.init(x: 0, y: 80, width: 200, height: 100))
imageView.image = image
self.view.addSubview(imageView)
}
}
六、閉包
閉包和block類似,有逃逸閉包和非逃逸閉包之分
//起別名
typealias AlertHandler = (_ action:UIAlertAction) -> () class JYShowAlert: NSObject { // 作為引數 class func showAlert(alertTitle:String,message:String,actionTitle:String,handler:@escaping AlertHandler){ let alertVC = UIAlertController.init(title:alertTitle, message: message, preferredStyle: UIAlertControllerStyle.alert) let confirm = UIAlertAction.init(title: actionTitle, style: UIAlertActionStyle.cancel, handler: handler) alertVC.addAction(confirm) let rootVC = UIApplication.shared.keyWindow?.rootViewController if ((rootVC?.presentedViewController) != nil){ rootVC?.presentedViewController?.present(alertVC, animated: true, completion: nil) }else{ rootVC?.present(alertVC, animated: true, completion: nil) } } }
七、橋接檔案
1、新建header-file
2、如下圖匯入
3、在檔案中加入需要橋接的objective-c的標頭檔案即可