MacOs-Swift开发-技巧记录

749 阅读1分钟

当下MacOs应用开发的文章太少了,碰到问题网上很难找到相应的中文解决方案,特此开帖记录一下。

1. NSWindow drag regions should only be invalidated on the Main Thread!

相信很多开发者都会碰到这个问题, 这个问题是在,其他线程去掉主UI线程的非法行为,属于跨线程操作了,MacOS不允许这样。 

在C#中我们一般用Delegates去解决这样问题。但其实在Swift中有一个内置的解决方案,就是用DispatchQueue这个类去解决,它本质上是一个队列任务调度器。但是它可以直接对主线程进行操作。

它有两种方式:DispatchQueue.main.async 异步处理 DispatchQueue.main.sync 同步处理

如果我们要在另一个线程中修改,主线程的UI怎么做?看下面代码

  DispatchQueue.global(qos: .default).async(execute: {

        DispatchQueue.main.async(execute: {
            self.labelMessage.text = "update text..."
        })
  })

2. Swift -Http 请求

 我们常用的方式就是采用URLSession, 

let session = URLSession.shared 
let url = URL(string:“ https://xxx.xxx.xxx/posts”)!

我们将创建一个dataTask调用URLSession.dataTask方法。这将创建一个任务,从URL集中检索内容,并在请求完成后调用处理程序

let task = session.dataTask(with:url,completeHandler :{data,responseerror in 
    //检查响应             
            print(error)              
            print(response)                                               
    })
task.resume()

接口返回数据进行JSON序列号处理,首先定义一个序列号化Codable对象

struct Message : Codable{    var code:Int    var msg:String    var data:String}

然后在接口中对返回的数据,进行decode操作

let task = session.dataTask(with:url,completeHandler :{data,response,error in 
       do{
            let result = try JSONDecoder().decode(Message.self, from: data! )            if result.code==200 {
                //do something...
            }
       }catch { 
            print("Error during JSON serialization: \(error.localizedDescription)") 
       }                                     
})
task.resume()

3 . Swift 定时器

   不多说,直接看代码:

 withTimeInterval 表示秒数,repeats表示是否重复

  Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { (ktimer) in             // print("定时器触发")
        //ktimer.invalidate()  关闭定时器  }