At present, there are too few articles about MacOs application development. It is difficult to find corresponding Chinese solutions on the Internet when encountering problems. Hereby I open a post to record.

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

I believe many developers will encounter this problem when other threads remove illegal behavior from the main UI thread, which is a cross-thread operation. MacOS does not allow this.

In C# we usually use Delegates to solve problems like this. But there is a built-in solution to this in Swift with the DispatchQueue class, which is essentially a queue task scheduler. But it can operate directly on the main thread.

It has two modes: dispatchqueue.main. async Asynchronous processing Dispatchqueue.main. sync Synchronous processing

If we want to modify the UI of the main thread in another thread, what do we do? Look at the following code

DispatchQueue.global(qos: .default).async(execute: { DispatchQueue.main.async(execute: { self.labelMessage.text = "update text..." })})Copy the code

2. Swift-http request

And the way we usually do that is we use URLSession,

Let the session = URLSession. Shared the let url = url (string: "https://xxx.xxx.xxx/posts")!Copy the code

We will create a dataTask and call the urlSession.datatask method. This creates a task that retrieves the content from the URL set and invokes the handler when the request completes

Let task = session.dataTask (with: url, completeHandler: {data, response, error in // check response print (error) print (response)}) task.resume ()Copy the code

The interface returns data for JSON sequence processing, first defining a serialized Codable object

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

Then decode the returned data in the interface

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 the JSON serialization: \ (Error. LocalizedDescription) ")}}) task. The resume ()Copy the code

3. Swift timer

Without further ado, let’s look at the code:

WithTimeInterval indicates the number of seconds, while repeats indicates whether it is repeated

Timer. ScheduledTimer (withTimeInterval: 2, repeats: true) {(ktimer) in // print(" Timer trigger ") //ktimer.invalidate() close Timer}}Copy the code