<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Võ Xuân Bách on Medium]]></title>
        <description><![CDATA[Stories by Võ Xuân Bách on Medium]]></description>
        <link>https://medium.com/@vobach1997ts?source=rss-9a64d82c8a78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6vNeyMy_LrtPCczuxb62TA.jpeg</url>
            <title>Stories by Võ Xuân Bách on Medium</title>
            <link>https://medium.com/@vobach1997ts?source=rss-9a64d82c8a78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:15:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vobach1997ts/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Easy render PDF with SwiftUI]]></title>
            <link>https://medium.com/@vobach1997ts/easy-render-pdf-with-swiftui-d5ae19d35c93?source=rss-9a64d82c8a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ae19d35c93</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Võ Xuân Bách]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 09:17:48 GMT</pubDate>
            <atom:updated>2024-01-05T09:40:39.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3RGU07lhu7c2jWvKj1VyA.png" /></figure><p>Hello everyone! Have you ever tried to render and export a PDF document in your iOS app? In this post, I will show you an easy but very efficient way to deal with it.</p><p>Firstly, you need to define the size of a PDF page. Let’s create constant variables to hold it. In this example, I want to render the PDF file at A4 size with 200 DPI resolution.</p><pre>let widthInPxl: CGFloat = 1654<br>let heightInPxl: CGFloat = 2229</pre><p>Next, check out the render PDF function.</p><pre>func renderPDF(pages: [AnyView], fileName: String) async throws -&gt; URL? {<br>    guard let rootVC = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.keyWindow?.rootViewController else {<br>        errorLog(&quot;rootVC is nil&quot;)<br>        return nil<br>    }<br>    <br>    guard let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {<br>        errorLog(&quot;documentDirectory is nil&quot;)<br>        return nil<br>    }<br>    let outputFileURL = documentDirectory.appendingPathComponent(fileName)<br>    <br>    debugLog(&quot;Rendering file: \(fileName)&quot;)<br>    <br>    // Add a view controller to the root, this view controller will hold your PDF views<br>    let pdfPage = UIHostingController(rootView: pages[0])<br>    pdfPage.view.frame = CGRect(x: 0, y: 0, width: widthInPxl, height: heightInPxl)<br>    rootVC.addChild(pdfPage)<br>    rootVC.view.insertSubview(pdfPage.view, at: 0)<br>    <br>    // If your view need to update after first rendering, this delay is needed<br>    try await Task.sleep(nanoseconds: 300_000_000)<br>    <br>    // Render the PDF<br>    let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: widthInPxl, height: heightInPxl))<br>    <br>    do {<br>        try pdfRenderer.writePDF(to: outputFileURL) { context in<br>            for page in pages {<br>                pdfPage.rootView = page<br>                context.beginPage()<br>                pdfPage.view.layer.render(in: context.cgContext)<br>            }<br>        }<br>    } catch {<br>        errorLog(&quot;Could not create PDF file: \(error)&quot;)<br>    }<br>    <br>    // Remove the view controller after finished<br>    pdfPage.willMove(toParent: nil)<br>    pdfPage.view.removeFromSuperview()<br>    pdfPage.removeFromParent()<br>    <br>    return outputFileURL<br>}</pre><p>The function takes 2 arguments:</p><ul><li>pages: The view of PDF pages you want to render.</li><li>fileName: The name of the PDF file. It will be stored temporarily at the device’s document folder.</li></ul><p><em>Pretty simple, right?</em></p><p>Now, I have some code to build a simple page view.</p><pre>@ViewBuilder<br>func simplePage(number: Int) -&gt; some View {<br>    VStack(spacing: 0) {<br>        Text(&quot;Page \(number)&quot;)<br>            .font(.system(size: 80))<br><br>        // Any code to build your PDF page view<br>    }<br>    .frame(width: widthInPxl, height: heightInPxl)<br>    .background(Color.white)<br>}</pre><p>Remember to set the size’s page view to equal the size’s PDF page we have defined before. Set the background to white (or any other colors). If not, the background of the PDF file will be black sometime (that is a bug).</p><p>Finally, export a PDF file.</p><pre>func exportToPDF() {<br>    var pageViews: [AnyView] = []<br>    <br>    for i in 1...1000 {<br>        pageViews.append(AnyView(simplePage(number: i)))<br>    }<br>    <br>    Task { @MainActor in<br>        isLoading = true<br>        if let url = try? await renderPDF(pages: pageViews, fileName: viewModel.getFileName(ext: &quot;pdf&quot;)) {<br>            shareURL(url)<br>        } else {<br>            // Handle unhappy case<br>        }<br>        isLoading = false<br>    }<br>}</pre><h4><strong>Conclusion</strong></h4><p>In my use case, I exported a 1000+ page PDF report file of light diagrams (also including images). The process only takes about 20 seconds and doesn’t cost too much performance. Quite impressive, I think. Since iOS 16, Apple released the <em>ImageRenderer class that </em>can be used to create PDFs. You might take a look.</p><p>Thank you so much for your reading. If you have any further questions or feedback, reach out at vobach1997ts@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ae19d35c93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have fun with BLE on iOS]]></title>
            <link>https://medium.com/@vobach1997ts/have-fun-with-ble-on-ios-0ee5a289fdca?source=rss-9a64d82c8a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ee5a289fdca</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bluetooth-low-energy]]></category>
            <dc:creator><![CDATA[Võ Xuân Bách]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 05:15:56 GMT</pubDate>
            <atom:updated>2024-01-03T05:15:56.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYFXh25k6k4FIegvD5Hhog.png" /></figure><p>Hello everyone! In this post, I will walk you through BLE technology and how to deal with it on iOS using Core Bluetooth. Let’s have fun.</p><p><strong>Bluetooth Low Energy (BLE)</strong> is a wireless technology that is designed to be low-power and low-cost. It is a subset of the Bluetooth standard and is compatible with most modern Bluetooth devices.</p><p>BLE is often used for applications where battery life is important, such as wearable devices, smart home devices, and industrial sensors. It is also used for applications where data transfer rates are not critical, such as beaconing and proximity detection.</p><p>Nowadays, Bluetooth is becoming very familiar to everyone. I use them almost every day. First of all, there are some basic terminologies we need to understand:</p><ol><li><strong>Peripheral</strong>: Devices that deliver the information demanded by the central</li><li><strong>Central</strong>: Devices that seek information from nearby peripherals.</li><li><strong>Services:</strong> Every device has multiple pieces of information which are categorized as services. These are discovered by central on successful connection with the peripheral.</li><li><strong>Characteristics: </strong>Data is stored and transferred as Characteristics listed under multiple services and are defined on BLE devices.</li></ol><p>Well, I will show you step-by-step how to work with BLE on iOS.</p><h3>Declare Bluetooth permission</h3><p>The app needs to use Bluetooth so we need to declare it in Info.plist. Add these lines into Info.plist file:</p><pre>&lt;key&gt;NSBluetoothAlwaysUsageDescription&lt;/key&gt;<br>&lt;string&gt;App needs bluetooth access to connect to nearby devices.&lt;/string&gt;</pre><h3>Scan for peripherals</h3><p>We can use CoreBluetooth to build a peripheral or a central as well. But in this post, we only focus on building a central application. Firstly, we create a class to manage BLE working.</p><pre>import CoreBluetooth<br><br>class BluetoothCentralManager: NSObject {<br>    private var centralManager: CBCentralManager!<br>    <br>    override init() {<br>        super.init()<br>        self.centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)<br>    }<br>}<br><br>extension BluetoothCentralManager: CBCentralManagerDelegate {<br>    func centralManagerDidUpdateState(_ central: CBCentralManager) {<br>        <br>    }<br>}</pre><p>Write a function to scan for peripherals. If you only want to scan specific peripherals, pass the peripheral&#39;s service UUID to the scanning function (otherwise, pass nil). We need to use <em>serviceCBUUID</em> again, so create a global variable to store it.</p><pre>private var serviceCBUUID: CBUUID?<br><br>private func scanForPeripherals() {<br>    guard centralManager.state == .poweredOn,<br>        let serviceUUID = NSUUID(uuidString: &quot;&lt;serviceUUID&gt;&quot;) as UUID? else {<br>        return<br>    }<br>    <br>    self.serviceCBUUID = CBUUID(nsuuid: serviceUUID)<br>    self.centralManager.scanForPeripherals(withServices: [serviceCBUUID!], options: nil)<br>}</pre><p>The scanning results will be returned at the <em>didDiscover</em> function of CBCentralManagerDelegate. Create a store property to store discovered peripherals.</p><pre>private var discoveredPeripherals: [UUID: CBPeripheral] = [:]<br><br>func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {<br>    self.discoveredPeripherals[peripheral.identifier] = peripheral<br>}</pre><p>To show discovered peripherals on UI, write a delegate for our central manager class.</p><pre>protocol BluetoothCentralDelegate: AnyObject {<br>    func didCentralUpdateState(state: CBManagerState)<br>    <br>    func didDiscoverPeripheral(uuid: String, name: String?)<br>    func didConnectPeripheral(uuid: String, name: String?)<br>    func didDisconnectPeripheral(uuid: String, name: String?)<br>    <br>    func didDiscoverCharacteristics()<br>    <br>    func didReceiveData(receivedData: Data)<br>    func didReceiveError(_ error: Error)<br>}</pre><p>In BluetoothCentralManager, create a delegate. Remember to use weak access control to avoid the retain cycle.</p><pre>weak var delegate: BluetoothCentralDelegate?<br><br>func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {<br>    self.discoveredPeripherals[peripheral.identifier] = peripheral<br>    // Updated here<br>    delegate?.didDiscoverPeripheral(uuid: peripheral.identifier.uuidString, name: peripheral.name)<br>}</pre><h3>Connect to the peripheral</h3><p>We can connect to the peripheral using the peripheral’s UUID. And add a delegate to the peripheral to get returned results.</p><pre>private var connectedPeripheral: CBPeripheral?<br><br>func connect(deviceId: String) {<br>    if let entry = discoveredPeripherals.first(where: { id, _ in<br>        id.uuidString == deviceId<br>    }) {<br>        self.connectedPeripheral = entry.value<br>        self.connectedPeripheral?.delegate = self<br>        self.centralManager.connect(entry.value, options: nil)<br>    }<br>}<br><br>extension BluetoothCentralManager: CBPeripheralDelegate {<br>    <br>}</pre><h3>Discover services</h3><p>After connecting to the peripheral successfully, we need to discover related services of the connected peripheral. If you don’t want to discover specific services, pass nil to the discovering function.</p><pre>extension BluetoothCentralManager: CBCentralManagerDelegate {<br>    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {<br>        self.delegate?.didConnectPeripheral(uuid: peripheral.identifier.uuidString, name: peripheral.displayName ?? &quot;&quot;)<br><br>        guard let serviceCBUUID: CBUUID = self.serviceCBUUID else { return }<br>        self.connectedPeripheral?.discoverServices([serviceCBUUID])<br>    }<br>}</pre><h3>Discover characteristics</h3><p>Each peripheral could have more than one service and each service could have more than one characteristic. In the didDiscoverServices delegate function, we will be able to discover multiple services, and then for each service, we will discover respective characteristics. If you don’t want to discover specific characteristics, pass nil to <em>discoverCharacteristics</em> function.</p><pre>private var inputCharacteristicCBUUID: CBUUID?<br>private var outputCharacteristicCBUUID: CBUUID?<br><br>extension BluetoothCentralManager: CBPeripheralDelegate {<br>    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {<br>        if let service: CBService = self.connectedPeripheral?.services?.first(where: { $0.uuid == self.serviceCBUUID }) {<br>            <br>            let inputCharacteristicUUID: UUID = NSUUID(uuidString: &quot;&lt;inputCharacteristicUUID&gt;&quot;)! as UUID<br>            let outputCharacteristicUUID: UUID = NSUUID(uuidString: &quot;&lt;outputCharacteristicUUID&gt;&quot;)! as UUID<br>            // send value to the peripheral<br>            self.inputCharacteristicCBUUID = CBUUID(nsuuid: inputCharacteristicUUID)<br>            // receive value from the peripheral<br>            self.outputCharacteristicCBUUID = CBUUID(nsuuid: outputCharacteristicUUID)<br>            <br>            self.connectedPeripheral?.discoverCharacteristics([inputCharacteristicCBUUID!, outputCharacteristicCBUUID!], for: service)<br>        }<br>    }<br>}</pre><h3>Read/Write data</h3><p>After discovering characteristics successfully, we can officially read and write data through the input/output characteristic. We need to set notify of the output characteristic to true. Anytime the output characteristic has been updated, we will get the notification. And keep a reference to the input characteristic. We will send data to the peripheral through it.</p><pre>private var inputCharacteristic: CBCharacteristic?<br><br>extension BluetoothCentralManager: CBPeripheralDelegate {<br>    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {<br>        if let characteristic: CBCharacteristic = service.characteristics?.first(where: { $0.uuid == self.outputCharacteristicCBUUID }) {<br>            // To listen and read dynamic values<br>            self.connectedPeripheral?.setNotifyValue(true, for: characteristic)<br>            <br>            // To read static values<br>            self.connectedPeripheral?.readValue(for: characteristic)<br>        }<br>        if let characteristic: CBCharacteristic = service.characteristics?.first(where: { $0.uuid == self.inputCharacteristicCBUUID }) {<br>            self.inputCharacteristic = characteristic<br>        }<br>        <br>        delegate?.didDiscoverCharacteristics()<br>        // The connection finally was established, no need to scan anymore<br>        self.centralManager.stopScan()<br>    }<br>}</pre><h4>Read data</h4><p>Information by peripheral would be sent in the form of data packets (unit: Byte), so each bit or byte represents the value we want. The data sent by the peripheral will be received at <em>didUpdateValueFor</em> delegate function. (Prerequisite: you need to know how each data is configured on the firmware side to understand the operation you need to perform on received data.)</p><pre>extension BluetoothCentralManager: CBPeripheralDelegate {    <br>    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {<br>        <br>        guard let value: Data = characteristic.value else {<br>            return<br>        }<br>        let bytes: [UInt8] = Array(value)<br>        // handleData(bytes)<br>    }<br>}</pre><p>This method is crucial for getting data sent by peripherals.</p><h4>Write data</h4><p>We will send data to the connected peripheral through the discovered input characteristic.</p><pre>func write(message: String) {<br>    guard let connectedPeripheral,<br>          let inputCharacteristic = self.inputCharacteristic else {<br>        return<br>    }<br>    <br>    let data = Data(message.utf8)<br>    <br>    connectedPeripheral.writeValue(data, for: inputCharacteristic, type: .withResponse)<br>}</pre><h3>Disconnect to the peripheral</h3><p>If you no longer want to connect to the peripheral or switch to other peripherals, use the <em>cancelPeripheralConnection</em> native function.</p><pre>func disconnect() {<br>    if connectedPeripheral != nil {<br>        self.centralManager.cancelPeripheralConnection(connectedPeripheral!)<br>        connectedPeripheral = nil<br>    }<br>}</pre><p>Well, done! That’s all basic steps we need to go through to communicate with Bluetooth devices. Moreover, there are a lot of delegate functions in <em>CBCentralManagerDelegate, and CBPeripheralDelegate </em>you might take a look.</p><p>Happy coding!</p><p>Thank you so much for your reading. If you have any further questions or feedback, reach out at vobach1997ts@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ee5a289fdca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>