• 2020-02-25
  • 2020-02-28

Introduction to Combine | How to connect to the Web Server with the Combine

This article explains that how to connect to the web server with the Combine. Create the Publisher of the DataTask Create the publisher of the data task to connect to the web server. Two methods are available to create it: The first method has an argument “URL”. If you want to simply connect to the URL and GET the contents, you can use this method. The second method has an argument “URLRequest”. With “URLRequest”, you can set the method of the HTTP, the body data, the header value and so on. You can handle most cases, but if wan to download the large file, you should use the download task of URLSession directly. Receiving Result To receive the result, use sink method. Returned value need to be keep in anywhere. You can write the code in following form: Keep in mind the thread Closures are executed on the sub-thread. Updating the GUI need to be executed on the main thread only. Sample Code Following code is a sample code. Enter the URL and tap the “GET” button, the application get the content from the URL with Combine. This code uses SwiftUI, you can copy & paste to the ContentView.swift and […]

  • 2020-02-24
  • 2020-02-28

Introduction to Combine | How to support Combine in a custom class

Combine is a framework to implement asynchronous operations. It is created by Apple, it is also used in Swift Data Binding. It is an important framework. If you new to Combine, see next article. If you want other samples, see following articles. This article explains how to support Combine in a custom class. Adopt to ObservableObject protocol. To make a class to support Combine, adopt to ObservableObject protocol. To notify a changes of properties with Combine, mark the property with @Published attribute. @Published The property which is marked with @Published attribute, can make the Publisher. Use $ operator to make the Publisher. Receive changes of properties of a custom class Use sink() to receive changes. The value of the property is not changed at the block is executing, so the value of the property is an old value yet. You should use a block argument “value”. Sample Application I made a sample application. “Hit” button decrement HP and “Heal” button recover it. I think this code will make you understand an effect of the ObservableObject.