<?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 Muhammed Yarbash K on Medium]]></title>
        <description><![CDATA[Stories by Muhammed Yarbash K on Medium]]></description>
        <link>https://medium.com/@muhammedyarbashk?source=rss-41d1ca4f4441------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fJ3iw6qN53PgsAZvu5eUkA.jpeg</url>
            <title>Stories by Muhammed Yarbash K on Medium</title>
            <link>https://medium.com/@muhammedyarbashk?source=rss-41d1ca4f4441------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:01:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammedyarbashk/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[  +    ( ) — …]]></title>
            <link>https://medium.com/@muhammedyarbashk/-e3badbb6b753?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3badbb6b753</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 06:38:46 GMT</pubDate>
            <atom:updated>2025-11-11T06:53:37.811Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 𝗙𝗹𝘂𝘁𝘁𝗲𝗿 + 𝗶𝗢𝗦 𝗦𝗵𝗮𝗿𝗲 𝗘𝘅𝘁𝗲𝗻𝘀𝗶𝗼𝗻 (𝗦𝘄𝗶𝗳𝘁𝗨𝗜 𝗨𝗜) — 𝗙𝘂𝗹𝗹 𝗜𝗻𝘁𝗲𝗴𝗿𝗮𝘁𝗶𝗼𝗻 𝗚𝘂𝗶𝗱𝗲</h3><p><em>I built a SwiftUI-based </em><strong><em>Share Extension</em></strong><em> for my Flutter app </em><strong><em>Thoughts — Inspiration Manager.</em></strong><em> Since the iOS Share Extension API still relies on UIKit, I implemented a custom integration that bridges Flutter and SwiftUI, allowing UI and data sharing between the extension and the main app.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x53rL-nqjhyBxGC0bSORFw.png" /></figure><p>My goal was to make any selected text shareable directly to my app through a Share Extension. The extension would present a custom SwiftUI sheet where users could edit the shared text and add extra details. While it sounds straightforward, the available documentation was sparse, and most tutorials I found were outdated or focused on UIKit — so I had to experiment and research quite a bit to get it working. In this guide, we’ll go through the complete process step by step.</p><h4>Step 1: Add the Share Extension Target</h4><ul><li>Go to <strong>File → New → Target</strong></li><li>Choose <strong>Share Extension</strong></li><li>Name it → ShareExtension</li><li>Uncheck “Include UI”</li><li>Language → <strong>Swift</strong></li><li>Click <strong>Finish</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QiF-WfBT6OsbL2iA0QKTg.png" /></figure><p>You will now find a new Group and some files in the Project Navigator. Xcode has automatically created a <em>UIViewController</em> subclass of type <em>SLComposeServiceViewController</em> in <em>ShareViewController.swift.</em> You’ll notice that by default Xcode has also created a <em>MainInterface.storyboard</em> and <em>Info.plist </em>file. You can run the project and test the default Share Extension, which was made to post content on a social media platform — not quite what we want yet, but you can give it a try.</p><h4>⚙️ 2. Enable App Groups</h4><p>To share data between the Share Extension and your Flutter app:</p><ol><li>In <strong>Runner → Signing &amp; Capabilities</strong>, click ➕ <strong>Capability → App Groups</strong></li><li>Create a group, e.g.</li></ol><pre>group.com.yourcompany.thoughts</pre><p>Add the same group in <strong>ShareExtension → Signing &amp; Capabilities</strong></p><p>This allows both targets to access the same shared container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqcNBTxh7kR_cb2HaoqWng.png" /></figure><h4>🧱 3. Create SwiftUI Share View</h4><pre>import SwiftUI<br>import UniformTypeIdentifiers<br><br>@objc(ShareViewController)<br>class ShareViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        let controller = UIHostingController(rootView: ShareView(extensionContext: self.extensionContext))<br>        addChild(controller)<br>        controller.view.frame = view.bounds<br>        view.addSubview(controller.view)<br>        controller.didMove(toParent: self)<br>    }<br>}<br><br>struct ShareView: View {<br>    var extensionContext: NSExtensionContext?<br><br>    @State private var sharedText: String = &quot;&quot;<br>    @State private var isCompleted = false<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;Share to Thoughts&quot;)<br>                .font(.title2)<br>                .bold()<br><br>            TextEditor(text: $sharedText)<br>                .frame(height: 120)<br>                .border(Color.gray.opacity(0.5))<br>                .padding(.horizontal)<br><br>            Button(&quot;Send to App&quot;) {<br>                saveSharedContent(sharedText)<br>                complete()<br>            }<br>            .buttonStyle(.borderedProminent)<br>            .tint(.blue)<br>        }<br>        .padding()<br>        .onAppear {<br>            loadSharedText()<br>        }<br>    }<br><br>    func loadSharedText() {<br>        guard let inputItems = extensionContext?.inputItems as? [NSExtensionItem],<br>              let item = inputItems.first else { return }<br><br>        if let attachments = item.attachments {<br>            for attachment in attachments {<br>                if attachment.hasItemConformingToTypeIdentifier(UTType.text.identifier) {<br>                    attachment.loadItem(forTypeIdentifier: UTType.text.identifier, options: nil) { (item, error) in<br>                        if let text = item as? String {<br>                            DispatchQueue.main.async {<br>                                sharedText = text<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    func saveSharedContent(_ content: String) {<br>        let defaults = UserDefaults(suiteName: &quot;group.com.yourcompany.thoughts&quot;)<br>        defaults?.set(content, forKey: &quot;shared_text&quot;)<br>        defaults?.synchronize()<br>    }<br><br>    func complete() {<br>        isCompleted = true<br>        extensionContext?.completeRequest(returningItems: [], completionHandler: nil)<br>    }<br>}</pre><h4>📄 4. Update Info.plist in the Extension</h4><p>Before we add custom UI, we have to configure the Share Extension. iOS needs to know for what kind of data your Share Extension should be shown. You can specify that in the <em>Info.plist</em> file of the Extension. By default you will see the key <em>NSExtensionActivationRule</em> has the value <em>TRUEPREDICATE</em> which means that the Share Extension will always be shown. Since we want our Share Extension only to be shown when Text was selected, we modify the<em> NSExtensionActivationRule</em>. Change the Type of the <em>NSExtensionActivationRule</em> from <em>String</em> to <em>Dictionary</em>. This will allow you to specify multiple allowed types. Click the small <strong>+ </strong>to create a new Item. Our Extension should only support Text, so add the key <em>NSExtensionActivationSupportsText </em>of Type<em> Boolean </em>and set the<em> </em>Value<em> </em>to<em> YES.</em></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt;<br>    &lt;string&gt;$(DEVELOPMENT_LANGUAGE)&lt;/string&gt;<br>    &lt;key&gt;CFBundleDisplayName&lt;/key&gt;<br>    &lt;string&gt;ShareExtension&lt;/string&gt;<br>    &lt;key&gt;CFBundleExecutable&lt;/key&gt;<br>    &lt;string&gt;$(EXECUTABLE_NAME)&lt;/string&gt;<br>    &lt;key&gt;CFBundleIdentifier&lt;/key&gt;<br>    &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br>    &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt;<br>    &lt;string&gt;6.0&lt;/string&gt;<br>    &lt;key&gt;CFBundleName&lt;/key&gt;<br>    &lt;string&gt;$(PRODUCT_NAME)&lt;/string&gt;<br>    &lt;key&gt;CFBundlePackageType&lt;/key&gt;<br>    &lt;string&gt;$(PRODUCT_BUNDLE_PACKAGE_TYPE)&lt;/string&gt;<br>    &lt;key&gt;CFBundleShortVersionString&lt;/key&gt;<br>    &lt;string&gt;1.0&lt;/string&gt;<br>    &lt;key&gt;CFBundleVersion&lt;/key&gt;<br>    &lt;string&gt;1&lt;/string&gt;<br>    &lt;key&gt;NSExtension&lt;/key&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;NSExtensionAttributes&lt;/key&gt;<br>        &lt;dict&gt;<br>            &lt;key&gt;NSExtensionActivationRule&lt;/key&gt;<br>            &lt;dict&gt;<br>                &lt;key&gt;NSExtensionActivationSupportsImageWithMaxCount&lt;/key&gt;<br>                &lt;integer&gt;10&lt;/integer&gt;<br>                &lt;key&gt;NSExtensionActivationSupportsMovieWithMaxCount&lt;/key&gt;<br>                &lt;integer&gt;5&lt;/integer&gt;<br>                &lt;key&gt;NSExtensionActivationSupportsText&lt;/key&gt;<br>                &lt;true/&gt;<br>                &lt;key&gt;NSExtensionActivationSupportsWebURLWithMaxCount&lt;/key&gt;<br>                &lt;integer&gt;1&lt;/integer&gt;<br>                &lt;key&gt;NSExtensionActivationSupportsFileWithMaxCount&lt;/key&gt;<br>                &lt;integer&gt;10&lt;/integer&gt;<br>            &lt;/dict&gt;<br>        &lt;/dict&gt;<br>        &lt;key&gt;NSExtensionMainStoryboard&lt;/key&gt;<br>        &lt;string&gt;MainInterface&lt;/string&gt;<br>        &lt;key&gt;NSExtensionPointIdentifier&lt;/key&gt;<br>        &lt;string&gt;com.apple.share-services&lt;/string&gt;<br>    &lt;/dict&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>Other Activation Rules are available, read more in <a href="https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/AppExtensionKeys.html#//apple_ref/doc/uid/TP40014212-SW2">Apple’s Developer Documentation</a>. After setting the Activation Rule, your Share Extension will only be shown in the system share sheet for the corresponding file types, in our case when Text is to be shared.</p><h4>🔗 5. Connect to Flutter</h4><pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;<br><br>class SharedContentHandler {<br>  static Future&lt;String?&gt; getSharedText() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    return prefs.getString(&#39;shared_text&#39;);<br>  }<br>}</pre><h4>Example usage in your HomePage:</h4><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;shared_content_handler.dart&#39;;<br><br>class HomePage extends StatefulWidget {<br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  String? sharedText;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    loadSharedData();<br>  }<br><br>  Future&lt;void&gt; loadSharedData() async {<br>    final text = await SharedContentHandler.getSharedText();<br>    if (text != null &amp;&amp; mounted) {<br>      setState(() =&gt; sharedText = text);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;Thoughts — Inspiration Manager&quot;)),<br>      body: Center(<br>        child: Text(sharedText ?? &quot;Share something from another app!&quot;),<br>      ),<br>    );<br>  }<br>}</pre><p>Now when you share selected text → choose your app → edit it in the SwiftUI sheet → open Flutter app → the shared text appears!</p><h4>Full code</h4><p><em>ShareExtensionView.swift:</em></p><pre>import UIKit<br>import Social<br>import UniformTypeIdentifiers<br>import UserNotifications<br><br>final class ShareViewController: SLComposeServiceViewController {<br><br>    // Use ONE shared group for both app &amp; extension (no &quot;.ShareExtension&quot; suffix)<br>    private let appGroupIdentifier = &quot;group.com.purposecodes.purposecolor&quot;<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        print(&quot; ShareViewController loaded&quot;)<br>        title = &quot;Share to PurposeColor&quot;<br>        placeholder = &quot;Add a comment (optional)&quot;<br>    }<br><br>    override func isContentValid() -&gt; Bool { true }<br><br>    override func didSelectPost() {<br>        print(&quot; Post button tapped&quot;)<br>        view.isUserInteractionEnabled = false<br><br>        guard<br>            let item = extensionContext?.inputItems.first as? NSExtensionItem,<br>            let providers = item.attachments, !providers.isEmpty<br>        else {<br>            print(&quot;⚠ No content found, completing anyway&quot;)<br>            completeExtension()<br>            return<br>        }<br><br>        print(&quot; Found \(providers.count) item(s) to process&quot;)<br>        processSharedContent(itemProviders: providers)<br>    }<br><br>    override func didSelectCancel() {<br>        print(&quot; Cancel button tapped&quot;)<br>        extensionContext?.cancelRequest(withError: NSError(domain: &quot;ShareExtension&quot;, code: -1))<br>    }<br><br>    // MARK: - Processing<br><br>    private func processSharedContent(itemProviders: [NSItemProvider]) {<br>        var sharedData: [String: Any] = [:]<br>        sharedData[&quot;text&quot;] = contentText ?? &quot;&quot;<br>        sharedData[&quot;timestamp&quot;] = Date().timeIntervalSince1970<br><br>        print(&quot;💬 Comment text: \(contentText ?? &quot;none&quot;)&quot;)<br><br>        let group = DispatchGroup()<br><br>        for (index, provider) in itemProviders.enumerated() {<br><br>            if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {<br>                print(&quot; Processing image at index \(index)&quot;)<br>                group.enter()<br>                provider.loadItem(forTypeIdentifier: UTType.image.identifier, options: nil) { [weak self] item, error in<br>                    defer { group.leave() }<br>                    if let error { print(&quot; Error loading image: \(error)&quot;); return }<br><br>                    var data: Data?<br>                    if let url = item as? URL {<br>                        data = try? Data(contentsOf: url)<br>                        print(&quot; Image loaded from URL&quot;)<br>                    } else if let d = item as? Data {<br>                        data = d<br>                        print(&quot; Image loaded as Data&quot;)<br>                    } else if let img = item as? UIImage {<br>                        data = img.jpegData(compressionQuality: 0.8)<br>                        print(&quot; Image loaded as UIImage&quot;)<br>                    }<br>                    if let data { self?.saveImageToAppGroup(data, index: index) }<br>                    sharedData[&quot;hasImages&quot;] = true<br>                    sharedData[&quot;imageCount&quot;] = (sharedData[&quot;imageCount&quot;] as? Int ?? 0) + 1<br>                }<br>            }<br>            else if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {<br>                print(&quot;🔗 Processing URL at index \(index)&quot;)<br>                group.enter()<br>                provider.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil) { item, _ in<br>                    defer { group.leave() }<br>                    if let url = item as? URL {<br>                        print(&quot; URL loaded: \(url.absoluteString)&quot;)<br>                        sharedData[&quot;url&quot;] = url.absoluteString<br>                    }<br>                }<br>            }<br>            else if provider.hasItemConformingToTypeIdentifier(UTType.text.identifier) {<br>                print(&quot;📝 Processing text at index \(index)&quot;)<br>                group.enter()<br>                provider.loadItem(forTypeIdentifier: UTType.text.identifier, options: nil) { item, _ in<br>                    defer { group.leave() }<br>                    if let text = item as? String {<br>                        print(&quot; Text loaded: \(text)&quot;)<br>                        sharedData[&quot;sharedText&quot;] = text<br>                    }<br>                }<br>            }<br>        }<br><br>        group.notify(queue: .main) { [weak self] in<br>            print(&quot; All items processed&quot;)<br>            self?.saveDataToAppGroup(sharedData)<br>            self?.completeExtension()<br>        }<br>    }<br><br>    private func saveImageToAppGroup(_ data: Data, index: Int) {<br>        guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else {<br>            print(&quot; Unable to access app group container&quot;)<br>            return<br>        }<br>        let fileURL = containerURL.appendingPathComponent(&quot;sharedImage\(index).jpg&quot;)<br>        do {<br>            try data.write(to: fileURL)<br>            print(&quot; Image saved to: \(fileURL.path)&quot;)<br>        } catch {<br>            print(&quot; Error saving image: \(error)&quot;)<br>        }<br>    }<br><br>    private func saveDataToAppGroup(_ dict: [String: Any]) {<br>        guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else {<br>            print(&quot; Unable to access app group container&quot;)<br>            return<br>        }<br>        print(&quot;📂 App Group container: \(containerURL.path)&quot;)<br>        let fileURL = containerURL.appendingPathComponent(&quot;sharedData.json&quot;)<br>        do {<br>            let json = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)<br>            try json.write(to: fileURL)<br>            print(&quot; Data saved to: \(fileURL.path)&quot;)<br>            print(&quot; Saved data: \(dict)&quot;)<br>        } catch {<br>            print(&quot; Error saving data: \(error)&quot;)<br>        }<br>    }<br><br>    // MARK: - Finish &amp; Open Host App (correct way)<br><br>    private func completeExtension() {<br>        print(&quot;Completing extension...&quot;)<br><br>        if let ud = UserDefaults(suiteName: appGroupIdentifier) {<br>            ud.set(true, forKey: &quot;hasNewSharedContent&quot;)<br>            ud.set(Date().timeIntervalSince1970, forKey: &quot;lastShareTimestamp&quot;)<br>            // ud.synchronize() // ← not needed; remove to reduce CFPrefs chatter<br>            print(&quot; Set hasNewSharedContent flag&quot;)<br>            self.completeAndNotifyUser()<br><br>        }<br><br>        // Dismiss first, then open host app via the extension API<br>        extensionContext?.completeRequest(returningItems: nil) { [weak self] _ in<br>            DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {<br>                self?.openMainApp()<br>            }<br>        }<br>    }<br><br>    private func openMainApp() {<br>        // add a unique param to avoid iOS “debounce” of identical repeated opens<br>        let urlString = &quot;purposecolor://share?ts=\(Int(Date().timeIntervalSince1970))&quot;<br>        guard let url = URL(string: urlString) else { return }<br>        print(&quot;🚀 Trying to open host app with: \(url.absoluteString)&quot;)<br>        extensionContext?.open(url) { ok in<br>            print(ok ? &quot; Opened host app&quot; : &quot; Could not open host app&quot;)<br>        }<br>    }<br><br>    func completeAndNotifyUser() {<br>        // Step 1: Extension close <br>        self.extensionContext?.completeRequest(returningItems: nil)<br><br>        // Step 2: Notification permission + local notification ]<br>        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, _ in<br>            if granted {<br>                let content = UNMutableNotificationContent()<br>                content.title = &quot;Shared to PurposeColor&quot;<br>                content.body = &quot;Tap to open and continue your post.&quot;<br>                content.sound = .default<br><br>                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)<br>                let request = UNNotificationRequest(identifier: UUID().uuidString,<br>                                                    content: content,<br>                                                    trigger: trigger)<br>                UNUserNotificationCenter.current().add(request)<br>            }<br>        }<br>    }<br><br><br>}</pre><p>SharePostView<em>.swift:</em></p><pre>import SwiftUI<br><br>struct SharePostView: View {<br>    @Environment(\.dismiss) var dismiss<br>    @State private var sharedData: SharedContentData?<br>    @State private var isLoading = true<br>    <br>    let appGroupIdentifier = &quot;group.com.purposecodes.purposecolor&quot;<br>    <br>    var body: some View {<br>        NavigationView {<br>            ZStack {<br>                Color(.systemGroupedBackground)<br>                    .ignoresSafeArea()<br>                <br>                if isLoading {<br>                    VStack(spacing: 16) {<br>                        ProgressView()<br>                        Text(&quot;Loading shared content...&quot;)<br>                            .foregroundColor(.secondary)<br>                    }<br>                } else if let data = sharedData {<br>                    ScrollView {<br>                        VStack(spacing: 20) {<br>                            // Header<br>                            Text(&quot;Shared Content&quot;)<br>                                .font(.title2)<br>                                .fontWeight(.bold)<br>                                .padding(.top)<br>                            <br>                            // Comment/Text<br>                            if let text = data.text, !text.isEmpty {<br>                                VStack(alignment: .leading, spacing: 8) {<br>                                    Text(&quot;Your Comment&quot;)<br>                                        .font(.headline)<br>                                        .foregroundColor(.secondary)<br>                                    <br>                                    Text(text)<br>                                        .padding()<br>                                        .frame(maxWidth: .infinity, alignment: .leading)<br>                                        .background(Color(.systemBackground))<br>                                        .cornerRadius(12)<br>                                }<br>                                .padding(.horizontal)<br>                            }<br>                            <br>                            // URL<br>                            if let url = data.url {<br>                                VStack(alignment: .leading, spacing: 8) {<br>                                    Text(&quot;Shared Link&quot;)<br>                                        .font(.headline)<br>                                        .foregroundColor(.secondary)<br>                                    <br>                                    Link(destination: URL(string: url)!) {<br>                                        HStack {<br>                                            Image(systemName: &quot;link.circle.fill&quot;)<br>                                                .foregroundColor(.blue)<br>                                            Text(url)<br>                                                .lineLimit(2)<br>                                                .foregroundColor(.blue)<br>                                            Spacer()<br>                                            Image(systemName: &quot;arrow.up.right.circle&quot;)<br>                                                .foregroundColor(.blue)<br>                                        }<br>                                        .padding()<br>                                        .background(Color(.systemBackground))<br>                                        .cornerRadius(12)<br>                                    }<br>                                }<br>                                .padding(.horizontal)<br>                            }<br>                            <br>                            // Shared Text<br>                            if let sharedText = data.sharedText, !sharedText.isEmpty {<br>                                VStack(alignment: .leading, spacing: 8) {<br>                                    Text(&quot;Shared Text&quot;)<br>                                        .font(.headline)<br>                                        .foregroundColor(.secondary)<br>                                    <br>                                    Text(sharedText)<br>                                        .padding()<br>                                        .frame(maxWidth: .infinity, alignment: .leading)<br>                                        .background(Color(.systemBackground))<br>                                        .cornerRadius(12)<br>                                }<br>                                .padding(.horizontal)<br>                            }<br>                            <br>                            // Images<br>                            if !data.images.isEmpty {<br>                                VStack(alignment: .leading, spacing: 8) {<br>                                    Text(&quot;Shared Images (\(data.images.count))&quot;)<br>                                        .font(.headline)<br>                                        .foregroundColor(.secondary)<br>                                        .padding(.horizontal)<br>                                    <br>                                    ScrollView(.horizontal, showsIndicators: false) {<br>                                        HStack(spacing: 12) {<br>                                            ForEach(data.images.indices, id: \.self) { index in<br>                                                Image(uiImage: data.images[index])<br>                                                    .resizable()<br>                                                    .scaledToFill()<br>                                                    .frame(width: 200, height: 200)<br>                                                    .clipShape(RoundedRectangle(cornerRadius: 12))<br>                                            }<br>                                        }<br>                                        .padding(.horizontal)<br>                                    }<br>                                }<br>                            }<br>                            <br>                            // Timestamp<br>                            if let timestamp = data.timestamp {<br>                                Text(&quot;Shared \(formattedDate(timestamp))&quot;)<br>                                    .font(.caption)<br>                                    .foregroundColor(.secondary)<br>                                    .padding(.top, 8)<br>                            }<br>                            <br>                            // Action Buttons<br>                            VStack(spacing: 12) {<br>                                Button(action: {<br>                                    print(&quot;💾 Save button tapped&quot;)<br>                                    // Add your save logic here<br>                                    // For example: save to Core Data, upload to server, etc.<br>                                }) {<br>                                    HStack {<br>                                        Image(systemName: &quot;square.and.arrow.down.fill&quot;)<br>                                        Text(&quot;Save to Library&quot;)<br>                                    }<br>                                    .frame(maxWidth: .infinity)<br>                                    .padding()<br>                                    .background(Color.blue)<br>                                    .foregroundColor(.white)<br>                                    .cornerRadius(12)<br>                                }<br>                                <br>                                Button(action: {<br>                                    print(&quot; Close button tapped&quot;)<br>                                    dismiss()<br>                                }) {<br>                                    HStack {<br>                                        Image(systemName: &quot;xmark.circle.fill&quot;)<br>                                        Text(&quot;Close&quot;)<br>                                    }<br>                                    .frame(maxWidth: .infinity)<br>                                    .padding()<br>                                    .background(Color(.systemGray5))<br>                                    .foregroundColor(.primary)<br>                                    .cornerRadius(12)<br>                                }<br>                            }<br>                            .padding(.horizontal)<br>                            .padding(.top, 20)<br>                        }<br>                        .padding(.bottom, 30)<br>                    }<br>                } else {<br>                    VStack(spacing: 16) {<br>                        Image(systemName: &quot;exclamationmark.triangle&quot;)<br>                            .font(.system(size: 60))<br>                            .foregroundColor(.orange)<br>                        <br>                        Text(&quot;No Shared Content&quot;)<br>                            .font(.title2)<br>                            .fontWeight(.semibold)<br>                        <br>                        Text(&quot;There&#39;s no content to display&quot;)<br>                            .foregroundColor(.secondary)<br>                        <br>                        Button(&quot;Close&quot;) {<br>                            dismiss()<br>                        }<br>                        .padding()<br>                        .background(Color.blue)<br>                        .foregroundColor(.white)<br>                        .cornerRadius(12)<br>                        .padding(.top)<br>                    }<br>                }<br>            }<br>            .navigationBarTitleDisplayMode(.inline)<br>            .toolbar {<br>                ToolbarItem(placement: .navigationBarTrailing) {<br>                    Button(&quot;Done&quot;) {<br>                        dismiss()<br>                    }<br>                }<br>            }<br>        }<br>        .onAppear {<br>            print(&quot; SharePostView appeared&quot;)<br>            loadSharedContent()<br>        }<br>    }<br>    <br>    let groupID = &quot;group.com.purposecodes.purposecolor&quot;<br><br>    func loadSharedContent() {<br>        guard let url = FileManager.default<br>            .containerURL(forSecurityApplicationGroupIdentifier: groupID)?<br>            .appendingPathComponent(&quot;sharedData.json&quot;) else { return }<br><br>        do {<br>            let data = try Data(contentsOf: url)<br>            let json = try JSONSerialization.jsonObject(with: data, options: [])<br>            print(&quot; Loaded shared JSON: \(json)&quot;)<br>            // handle and then optionally clear flag:<br>            UserDefaults(suiteName: groupID)?.set(false, forKey: &quot;hasNewSharedContent&quot;)<br>        } catch {<br>            print(&quot; Failed to read shared JSON: \(error)&quot;)<br>        }<br>    }<br><br>    <br>    private func getSharedContent() -&gt; SharedContentData? {<br>        guard let containerURL = FileManager.default.containerURL(<br>            forSecurityApplicationGroupIdentifier: appGroupIdentifier<br>        ) else {<br>            print(&quot; Unable to access app group container&quot;)<br>            return nil<br>        }<br>        <br>        print(&quot;App Group URL: \(containerURL.path)&quot;)<br>        <br>        let fileURL = containerURL.appendingPathComponent(&quot;sharedData.json&quot;)<br>        <br>        guard let data = try? Data(contentsOf: fileURL),<br>              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {<br>            print(&quot;No shared data found at: \(fileURL.path)&quot;)<br>            return nil<br>        }<br>        <br>        print(&quot; Found shared data: \(json)&quot;)<br>        <br>        // Get images<br>        var images: [UIImage] = []<br>        for i in 0..&lt;10 {<br>            let imageURL = containerURL.appendingPathComponent(&quot;sharedImage\(i).jpg&quot;)<br>            if let imageData = try? Data(contentsOf: imageURL),<br>               let image = UIImage(data: imageData) {<br>                images.append(image)<br>                print(&quot; Loaded image \(i)&quot;)<br>            }<br>        }<br>        <br>        // Create SharedContentData<br>        let contentData = SharedContentData(<br>            text: json[&quot;text&quot;] as? String,<br>            url: json[&quot;url&quot;] as? String,<br>            sharedText: json[&quot;sharedText&quot;] as? String,<br>            images: images,<br>            timestamp: json[&quot;timestamp&quot;] as? TimeInterval<br>        )<br>        <br>        // Clean up files after reading<br>        try? FileManager.default.removeItem(at: fileURL)<br>        for i in 0..&lt;10 {<br>            let imageURL = containerURL.appendingPathComponent(&quot;sharedImage\(i).jpg&quot;)<br>            try? FileManager.default.removeItem(at: imageURL)<br>        }<br>        print(&quot; Cleaned up shared files&quot;)<br>        <br>        // Clear the flag<br>        if let userDefaults = UserDefaults(suiteName: appGroupIdentifier) {<br>            userDefaults.set(false, forKey: &quot;hasNewSharedContent&quot;)<br>            userDefaults.synchronize()<br>            print(&quot;Cleared hasNewSharedContent flag&quot;)<br>        }<br>        <br>        return contentData<br>    }<br>    <br>    private func formattedDate(_ timestamp: TimeInterval) -&gt; String {<br>        let date = Date(timeIntervalSince1970: timestamp)<br>        let formatter = RelativeDateTimeFormatter()<br>        formatter.unitsStyle = .full<br>        return formatter.localizedString(for: date, relativeTo: Date())<br>    }<br>}<br><br>// Data model<br>struct SharedContentData {<br>    let text: String?<br>    let url: String?<br>    let sharedText: String?<br>    let images: [UIImage]<br>    let timestamp: TimeInterval?<br>}<br><br>// Preview<br>//struct SharePostView_Previews: PreviewProvider {<br>//    static var previews: some View {<br>//        SharePostView()<br>//    }<br>//}</pre><h4>ShareExtension Info <strong>plist</strong>:</h4><p>Thanks for taking the time to read through! I hope this guide makes your setup a bit easier and saves you from the same trial and error I went through 😄</p><p>Got suggestions or improvements? Drop them in — I’d love to hear your thoughts and learn together.</p><p>You can try out my app <em>Thoughts — Inspiration Manager</em> (free on the App Store) to see how the Share Extension works in real life!</p><p>— <em>Cheers,</em><br> <strong>Muhammed Yarbash K</strong></p><h4>Helpful links</h4><ul><li><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/Share.html">https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/Share.html</a></li><li><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW8">https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW8</a></li><li><a href="https://medium.com/macoclock/ios-share-extension-swift-5-1-1606263746b">https://medium.com/macoclock/ios-share-extension-swift-5-1-1606263746b</a></li><li><a href="https://www.9series.com/blog/build-share-extension-ios-using-swift/">https://www.9series.com/blog/build-share-extension-ios-using-swift/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3badbb6b753" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Customize Your SwiftUI Chat App with Firebase and Push Notifications ]]></title>
            <link>https://medium.com/@muhammedyarbashk/how-to-customize-your-swiftui-chat-app-with-firebase-and-push-notifications-3359c782be78?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/3359c782be78</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 07:55:10 GMT</pubDate>
            <atom:updated>2025-10-09T07:55:10.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNCK6626guT5pkLcPGoqMw.png" /></figure><h3>Introduction</h3><p>Want to build a unique chat experience in your iOS app? With SwiftUI, Firebase for messaging, and Push Notifications for real-time updates, you can create a robust, customized chat app for your users!</p><h3>1. Setting Up Firebase for Messaging</h3><p>Step-by-step basics on integrating Firebase:</p><ul><li>Add Firebase SDK to your project via Swift Package Manager or CocoaPods.</li><li>Configure Firebase in your AppDelegate.</li><li>Set up authentication (e.g., Email/password, phone).</li></ul><pre>import FirebaseCore<br><br>@main<br>struct YourApp: App {<br>    init() {<br>        FirebaseApp.configure()<br>    }<br>}</pre><h3>2. Building a Custom Chat UI in SwiftUI</h3><ul><li>Create a reusable ChatMessageRow view.</li><li>List messages with a scrollable view.</li><li>Enable message input and sending.</li></ul><pre>struct ChatView: View {<br>    @State private var messages: [Message] = []<br>    @State private var newMessage = &quot;&quot;<br><br>    var body: some View {<br>        VStack {<br>            ScrollView {<br>                ForEach(messages) { message in<br>                    ChatMessageRow(message: message)<br>                }<br>            }<br>            HStack {<br>                TextField(&quot;Type a message...&quot;, text: $newMessage)<br>                Button(&quot;Send&quot;) { sendMessage(newMessage) }<br>            }<br>            .padding()<br>        }<br>        .onAppear(perform: loadMessages)<br>    }<br><br>    func sendMessage(_ text: String) {<br>        // Push message to Firebase<br>    }<br><br>    func loadMessages() {<br>        // Observe Firebase for new messages<br>    }<br>}</pre><h3>3. Observing and Throwing Firebase Messages</h3><ul><li>Use real-time listeners to update your chat UI instantly.</li><li>Detach listeners in onDisappear to prevent memory leaks.</li></ul><pre>import FirebaseDatabase<br><br>func loadMessages() {<br>    let ref = Database.database().reference().child(&quot;chat/messages&quot;)<br>    ref.observe(.childAdded) { snapshot in<br>        // Parse and append new messages<br>    }<br>}</pre><h3>4. Integrating Push Notifications</h3><p>Make sure users get notifications for new messages!</p><ul><li>Enable Firebase Cloud Messaging (FCM) in your Firebase Console.</li><li>Add notification permissions and background handling.</li><li>Handle push notifications in your app, update UI on message arrival.</li></ul><pre>import FirebaseMessaging<br><br>class AppDelegate: NSObject, UIApplicationDelegate, MessagingDelegate {<br>    func application(_ application: UIApplication,<br>                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {<br>        Messaging.messaging().apnsToken = deviceToken<br>    }<br><br>    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {<br>        // Send the token to your server<br>    }<br>}</pre><h3>5. Customizing the UI and Experience</h3><ul><li>Add avatars, colors, reactions, etc.</li><li>Support read receipts, typing indicators.</li><li>Use custom transitions and layout with SwiftUI.</li></ul><h3>Conclusion</h3><p>By following these steps, you’ll create a customizable chat app with Firebase and push notifications in SwiftUI.<br>Personalize your UI, enhance features — and build a brilliant messaging experience your users will love! 🎉</p><p>Ready to get started? Dive in and make your chat app truly yours!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3359c782be78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚡ SwiftUI + BLE: Build Bluetooth-Powered iOS Apps ]]></title>
            <link>https://medium.com/@muhammedyarbashk/swiftui-ble-build-bluetooth-powered-ios-apps-0f28a15b07eb?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f28a15b07eb</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 09:31:53 GMT</pubDate>
            <atom:updated>2025-04-07T09:31:53.358Z</atom:updated>
            <content:encoded><![CDATA[<p>⚙️ Understanding CoreBluetooth: The Heart of iOS BLE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gvJqzWXIh95mqg3_BTF8g.png" /></figure><p>Bluetooth Low Energy (BLE) is widely used in modern apps that interact with smartwatches, fitness bands, home automation devices, and various IoT gadgets. If you’re building an iOS app that needs to communicate wirelessly with nearby devices while preserving battery life, BLE is your go-to solution.</p><p>In this article, you’ll learn how to build a <strong>Bluetooth-ready iOS app using Swift and CoreBluetooth</strong>, with a SwiftUI-compatible structure. Whether you’re a beginner or looking to polish your BLE knowledge, this step-by-step guide is designed for you.</p><h3>Basic BLE Terminology</h3><p>To work effectively with BLE in iOS, it’s important to understand the core terms used in Bluetooth communication. These concepts form the foundation of how devices discover, connect, and exchange data over BLE:</p><ul><li><strong>Central</strong>: The device (usually your iPhone or iPad) that initiates the connection and scans for peripherals.</li><li><strong>Peripheral</strong>: The device that advertises data and awaits connection from a central (e.g., a fitness band or heart rate monitor).</li><li><strong>Service</strong>: A collection of related data and behaviors exposed by a peripheral.</li><li><strong>Characteristic</strong>: A specific piece of data within a service, used to read or write values.</li><li><strong>UUID (Universal Unique Identifier)</strong>: A unique identifier assigned to services and characteristics.</li><li><strong>RSSI (Received Signal Strength Indicator)</strong>: A value indicating the signal strength from a peripheral — useful for estimating distance.</li></ul><h3>Getting Started</h3><p>First, make sure you have access to a <strong>working BLE peripheral device</strong> — one that can <strong>broadcast advertising data</strong> and respond to connection requests. This is essential for testing and interacting with BLE functionality from your iOS app.</p><p>Below is a basic <strong>flowchart</strong> that illustrates how BLE communication works in Swift using the <strong>CoreBluetooth</strong> framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kpd-88KdE3gjHZOHC9DdA.png" /></figure><h3>Integrating BLE with CoreBluetooth in Swift</h3><p>Now it’s time to implement <strong>BLE functionality</strong> in your iOS application using Apple’s <strong>CoreBluetooth framework</strong> in <strong>Swift</strong>. In this section, we’ll walk through the essential steps required to <strong>discover BLE devices</strong>, <strong>establish connections</strong>, and <strong>interact with peripheral services and characteristics</strong>. These fundamentals will give you a strong foundation for integrating BLE into your apps — whether you’re working on fitness trackers, smart home devices, or any Bluetooth-enabled solution.</p><h3>Build Bluetooth-Ready iOS Apps Using Swift &amp; CoreBluetooth</h3><p>In this step-by-step guide, you’ll learn how to <strong>discover</strong>, <strong>connect</strong>, <strong>interact</strong>, and <strong>exchange data</strong> with BLE (Bluetooth Low Energy) peripherals using <strong>Swift</strong> and <strong>CoreBluetooth</strong>.</p><h3>1. Project Setup</h3><p><strong>Permissions:</strong><br> Add the following key-value pair in your Info.plist file to allow Bluetooth access:</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;<br></pre><ul><li>Import CoreBluetooth:</li></ul><pre>import CoreBluetooth</pre><h3>2. BLEViewModel.swift – Scan &amp; Connect Logic</h3><p>Create a BLEViewModel with ObservableObject, CBCentralManagerDelegate, and CBPeripheralDelegate.</p><pre>class BLEViewModel: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {<br>    var centralManager: CBCentralManager!<br>    @Published var peripherals: [CBPeripheral] = []<br>    @Published var connectedPeripheral: CBPeripheral?<br>    <br>    override init() {<br>        super.init()<br>        centralManager = CBCentralManager(delegate: self, queue: .main)<br>    }<br><br>    func centralManagerDidUpdateState(_ central: CBCentralManager) {<br>        if central.state == .poweredOn {<br>            centralManager.scanForPeripherals(withServices: nil)<br>        }<br>    }<br><br>    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,<br>                        advertisementData: [String : Any], rssi RSSI: NSNumber) {<br>        if !peripherals.contains(where: { $0.identifier == peripheral.identifier }) {<br>            peripherals.append(peripheral)<br>        }<br>    }<br><br>    func connect(to peripheral: CBPeripheral) {<br>        centralManager.stopScan()<br>        connectedPeripheral = peripheral<br>        peripheral.delegate = self<br>        centralManager.connect(peripheral)<br>    }<br>}</pre><h3>3. Display Devices in Table &amp; Connect on Tap</h3><pre>struct BLEDeviceListView: View {<br>    @ObservedObject var bleViewModel = BLEViewModel()<br><br>    var body: some View {<br>        NavigationView {<br>            List(bleViewModel.peripherals, id: \.identifier) { peripheral in<br>                Button(action: {<br>                    bleViewModel.connect(to: peripheral)<br>                }) {<br>                    Text(peripheral.name ?? &quot;Unknown Device&quot;)<br>                }<br>            }<br>            .navigationTitle(&quot;BLE Devices&quot;)<br>        }<br>    }<br>}</pre><h3>4. DidConnect — Discover Services</h3><p>In BLEViewModel:</p><pre>func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {<br>    print(&quot;Connected to \(peripheral.name ?? &quot;Device&quot;)&quot;)<br>    peripheral.discoverServices(nil)<br>}</pre><h3>5. Discover Services and Characteristics</h3><p>Add this to BLEViewModel:</p><pre>func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {<br>    if let services = peripheral.services {<br>        for service in services {<br>            peripheral.discoverCharacteristics(nil, for: service)<br>        }<br>    }<br>}</pre><h3>6. Discover Specific Characteristics</h3><pre>func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {<br>    if let characteristics = service.characteristics {<br>        for characteristic in characteristics {<br>            print(&quot;Found characteristic: \(characteristic.uuid)&quot;)<br>            // Optional: Auto-read or save reference<br>            peripheral.readValue(for: characteristic)<br>        }<br>    }<br>}</pre><h3>7. Read Values From Characteristics</h3><pre>func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {<br>    if let value = characteristic.value {<br>        let dataString = String(decoding: value, as: UTF8.self)<br>        print(&quot;Read value: \(dataString)&quot;)<br>    }<br>}</pre><p>⚠️ <strong>Note:</strong> Understand the peripheral’s data format before decoding values. Each characteristic might represent a different kind of data, and byte structure depends on firmware.</p><h3>8. Write Data to Peripheral</h3><p>To send data to a BLE peripheral in Swift, you use the writeValue method provided by the CBPeripheral class. This function requires three parameters:</p><ol><li><strong>The data</strong> you want to send (Data type),</li><li><strong>The characteristic</strong> you’re writing to (CBCharacteristic),</li><li><strong>The write type</strong>, which can be either:</li></ol><ul><li>.withResponse: The peripheral will acknowledge receipt.</li><li>.withoutResponse: No acknowledgment is expected (faster, but less reliable).</li></ul><blockquote><em>📝 The supported write type (</em><em>withResponse or </em><em>withoutResponse) depends on the peripheral’s characteristic configuration, which is defined by the device manufacturer.</em></blockquote><pre>func writeData(to characteristic: CBCharacteristic, on peripheral: CBPeripheral, value: String) {<br>    if let data = value.data(using: .utf8) {<br>        peripheral.writeValue(data, for: characteristic, type: .withResponse)<br>        print(&quot;✉️ Wrote data: \(value)&quot;)<br>    }<br>}</pre><h3>Alternative BLE Code Example</h3><pre>import Foundation<br>import CoreBluetooth<br><br>class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {<br>    @Published var peripherals: [CBPeripheral] = []<br>    @Published var connectedPeripheral: CBPeripheral?<br>    @Published var receivedValue: String = &quot;&quot;<br>    <br>    private var centralManager: CBCentralManager!<br>    private var targetCharacteristic: CBCharacteristic?<br><br>    override init() {<br>        super.init()<br>        centralManager = CBCentralManager(delegate: self, queue: .main)<br>    }<br><br>    func centralManagerDidUpdateState(_ central: CBCentralManager) {<br>        if central.state == .poweredOn {<br>            centralManager.scanForPeripherals(withServices: nil)<br>            print(&quot;Scanning...&quot;)<br>        } else {<br>            print(&quot;Bluetooth not ready&quot;)<br>        }<br>    }<br><br>    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,<br>                        advertisementData: [String : Any], rssi RSSI: NSNumber) {<br>        if !peripherals.contains(where: { $0.identifier == peripheral.identifier }) {<br>            peripherals.append(peripheral)<br>        }<br>    }<br><br>    func connect(to peripheral: CBPeripheral) {<br>        centralManager.stopScan()<br>        connectedPeripheral = peripheral<br>        peripheral.delegate = self<br>        centralManager.connect(peripheral, options: nil)<br>    }<br><br>    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {<br>        print(&quot;Connected to \(peripheral.name ?? &quot;Device&quot;)&quot;)<br>        peripheral.discoverServices(nil)<br>    }<br><br>    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {<br>        if let services = peripheral.services {<br>            for service in services {<br>                peripheral.discoverCharacteristics(nil, for: service)<br>            }<br>        }<br>    }<br><br>    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {<br>        guard let characteristics = service.characteristics else { return }<br>        for characteristic in characteristics {<br>            print(&quot;Found: \(characteristic.uuid)&quot;)<br>            targetCharacteristic = characteristic<br>            peripheral.readValue(for: characteristic)<br>        }<br>    }<br><br>    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {<br>        if let value = characteristic.value {<br>            receivedValue = String(decoding: value, as: UTF8.self)<br>        }<br>    }<br><br>    func writeData(_ text: String) {<br>        guard let peripheral = connectedPeripheral,<br>              let characteristic = targetCharacteristic,<br>              let data = text.data(using: .utf8) else { return }<br><br>        peripheral.writeValue(data, for: characteristic, type: .withResponse)<br>        print(&quot;✉️ Sent: \(text)&quot;)<br>    }<br>}</pre><h3>Bonus BLE Tips for SwiftUI + CoreBluetooth</h3><h3>1. Filtering Magic (Smart Scanning)</h3><p>Instead of scanning for <strong>all devices</strong>, filter based on services:</p><pre>let serviceUUID = CBUUID(string: &quot;FFE0&quot;) // Replace with your target<br>centralManager.scanForPeripherals(withServices: [serviceUUID])</pre><p>🔋 This <strong>improves performance</strong> and <strong>saves battery</strong> by ignoring irrelevant devices.</p><h3>2. Leverage UUIDs &gt; Names</h3><p>🛑 Don’t rely on .name — it&#39;s often <strong>nil</strong> or duplicated.</p><p>Use <strong>Service UUIDs</strong> or <strong>Characteristic UUIDs</strong> to target specific hardware:</p><pre>let knownServiceUUID = CBUUID(string: &quot;180D&quot;) // Heart Rate Monitor<br>let characteristicUUID = CBUUID(string: &quot;2A37&quot;)</pre><p>UUIDs = your <strong>BLE fingerprint</strong>.</p><h3>3. Set a Scan Timeout</h3><p>Avoid scanning forever. Add a timeout:</p><pre>DispatchQueue.main.asyncAfter(deadline: .now() + 10) {<br>    self.centralManager.stopScan()<br>    print(&quot;Scan stopped after 10 seconds&quot;)<br>}</pre><p>This keeps your app <strong>efficient</strong> and avoids <strong>battery drain</strong>.</p><h3>Extra Pro Tips</h3><ul><li><strong>Clean duplicates</strong> in your list by checking .identifier</li><li>Always call .stopScan() before connecting</li><li>Prefer .withResponse for writeValue when confirmation matters</li><li>Use .readValue(for:) only after characteristics are discovered</li><li>Watch the <strong>Bluetooth state</strong> before scanning (.poweredOn only)</li></ul><h3>Wrap Up</h3><p>These little touches make a <strong>huge impact</strong> when building <strong>real-world BLE apps</strong>.</p><blockquote><em>️ Mastering BLE isn’t about more code — it’s about </em><strong><em>smarter code</em></strong><em>.</em></blockquote><p>Let me know if you want:</p><ul><li>A test peripheral simulator</li><li>Background BLE scanning setup</li><li>Notify-based real-time streaming</li></ul><p>Happy Coding and BLE-ing! 💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f28a15b07eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking AVFoundation in Swift: The Ultimate Developer’s Guide ]]></title>
            <link>https://medium.com/@muhammedyarbashk/the-media-magician-transforming-swift-apps-with-avfoundation-bff7600104d2?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/bff7600104d2</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 09:16:06 GMT</pubDate>
            <atom:updated>2025-03-11T10:46:16.421Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Multimedia capabilities are at the core of modern iOS applications, and Apple’s <strong>AVFoundation</strong> framework stands as the cornerstone for sophisticated audio and video handling. This powerful framework enables developers to create seamless multimedia experiences — from basic playback to complex editing workflows.</p><p>This comprehensive guide explores AVFoundation’s most powerful features with practical code examples, troubleshooting advice, and optimization techniques that will elevate your iOS applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*r2srQQwSAXZOHUGtRAnLog.jpeg" /></figure><h3>Understanding AVFoundation’s Architecture</h3><p>Before diving into implementation details, it’s crucial to understand how AVFoundation’s components work together:</p><ul><li><strong>Assets</strong>: Represented by AVAsset, these abstract representations of media files provide metadata and timing information.</li><li><strong>Players</strong>: Components like AVPlayer handle the playback of assets.</li><li><strong>Capture</strong>: The AVCaptureSession coordinates the flow of data from input devices to outputs.</li><li><strong>Composition</strong>: Tools such as AVMutableComposition enable the creation and modification of temporal arrangements.</li><li><strong>Export</strong>: Classes like AVAssetExportSession facilitate the export of composed media.</li></ul><p>This layered architecture provides both flexibility and power for complex media operations.</p><h3>1. Advanced Video Playback with AVPlayer</h3><p>While the basics of video playback are straightforward, mastering AVPlayer requires understanding its more advanced capabilities:</p><pre><br>import AVFoundation<br>import AVKit<br>import UIKit<br><br>class EnhancedVideoPlayerViewController: UIViewController {<br>    private var player: AVPlayer?<br>    private var playerItem: AVPlayerItem?<br>    private var timeObserverToken: Any?<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupPlayer()<br>    }<br>    <br>    private func setupPlayer() {<br>        guard let url = URL(string: &quot;https://example.com/video.mp4&quot;) else { return }<br>        <br>        // Create an asset with loading options for better performance<br>        let asset = AVAsset(url: url)<br>        let assetKeys = [&quot;playable&quot;, &quot;duration&quot;, &quot;tracks&quot;]<br>        <br>        // Create a player item with the asset<br>        playerItem = AVPlayerItem(asset: asset, automaticallyLoadedAssetKeys: assetKeys)<br>        playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.new, .initial], context: nil)<br>        <br>        // Create the player<br>        player = AVPlayer(playerItem: playerItem)<br>        <br>        // Add time observer for progress tracking<br>        addPeriodicTimeObserver()<br>        <br>        // Configure and present the player controller<br>        let playerViewController = AVPlayerViewController()<br>        playerViewController.player = player<br>        <br>        // Enable picture-in-picture if supported<br>        playerViewController.canStartPictureInPictureAutomaticallyFromInline = true<br>        <br>        present(playerViewController, animated: true) {<br>            self.player?.play()<br>        }<br>    }<br>    <br>    private func addPeriodicTimeObserver() {<br>        // Observe playback timing at 0.5 second intervals<br>        let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC))<br>        timeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in<br>            // Update UI with current playback time<br>            let seconds = CMTimeGetSeconds(time)<br>            print(&quot;Current playback time: \(seconds)&quot;)<br>        }<br>    }<br>    <br>    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {<br>        if keyPath == #keyPath(AVPlayerItem.status) {<br>            let status: AVPlayerItem.Status<br>            if let statusNumber = change?[.newKey] as? NSNumber {<br>                status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!<br>            } else {<br>                status = .unknown<br>            }<br>            <br>            // Handle player item status changes<br>            switch status {<br>            case .readyToPlay:<br>                print(&quot;Ready to play&quot;)<br>            case .failed:<br>                print(&quot;Failed to load: \(playerItem?.error?.localizedDescription ?? &quot;Unknown error&quot;)&quot;)<br>            case .unknown:<br>                print(&quot;Status unknown&quot;)<br>            @unknown default:<br>                print(&quot;Unhandled status&quot;)<br>            }<br>        }<br>    }<br>    <br>    override func viewWillDisappear(_ animated: Bool) {<br>        super.viewWillDisappear(animated)<br>        <br>        // Remove observer when view disappears<br>        if let timeObserverToken = timeObserverToken {<br>            player?.removeTimeObserver(timeObserverToken)<br>            self.timeObserverToken = nil<br>        }<br>        <br>        playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status))<br>    }<br>}</pre><h3>Key Optimization Techniques</h3><ol><li><strong>Adaptive Streaming</strong></li></ol><pre>// Configure for HTTP Live Streaming<br>let playerItem = AVPlayerItem(asset: asset)<br>playerItem.preferredForwardBufferDuration = 10.0  // Buffer 10 seconds ahead<br>playerItem.preferredPeakBitRate = 2000000  // Limit to 2Mbps for slower connections</pre><p><strong>2. Background Playback</strong></p><pre>// In AppDelegate or relevant setup code<br>do {<br>    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)<br>    try AVAudioSession.sharedInstance().setActive(true)<br>} catch {<br>    print(&quot;Failed to configure audio session: \(error)&quot;)<br>}</pre><p><strong>3. Custom Controls with AVPlayerLayer</strong></p><pre>let playerLayer = AVPlayerLayer(player: player)<br>playerLayer.frame = customPlayerView.bounds<br>playerLayer.videoGravity = .resizeAspectFill<br>customPlayerView.layer.addSublayer(playerLayer)2. Professional Audio and Video Recording</pre><h3>2. Professional Audio and Video Recording</h3><p>Recording high-quality media requires understanding both the capabilities and limitations of the device hardware:</p><p>Recording high-quality media requires understanding both the capabilities and limitations of the device hardware:</p><pre>import AVFoundation<br>import UIKit<br><br>class ProfessionalMediaRecorder: NSObject {<br>    private let captureSession = AVCaptureSession()<br>    private var audioOutput: AVCaptureAudioDataOutput?<br>    private var videoOutput: AVCaptureMovieFileOutput?<br>    private var captureDevice: AVCaptureDevice?<br>    <br>    func setupRecordingSession() {<br>        // Configure capture session for high quality<br>        if captureSession.canSetSessionPreset(.high) {<br>            captureSession.sessionPreset = .high<br>        }<br>        <br>        // Request permissions<br>        requestCameraAndMicrophoneAccess { granted in<br>            guard granted else {<br>                print(&quot;Camera and microphone permissions required&quot;)<br>                return<br>            }<br>            <br>            self.configureCaptureDevices()<br>            self.configureVideoOutput()<br>        }<br>    }<br>    <br>    private func requestCameraAndMicrophoneAccess(completion: @escaping (Bool) -&gt; Void) {<br>        var cameraGranted = false<br>        var microphoneGranted = false<br>        <br>        let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)<br>        let microphoneAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)<br>        <br>        let checkCompletion = {<br>            DispatchQueue.main.async {<br>                completion(cameraGranted &amp;&amp; microphoneGranted)<br>            }<br>        }<br>        <br>        // Handle camera authorization<br>        switch cameraAuthorizationStatus {<br>        case .authorized:<br>            cameraGranted = true<br>            if microphoneAuthorizationStatus != .notDetermined {<br>                checkCompletion()<br>            }<br>        case .notDetermined:<br>            AVCaptureDevice.requestAccess(for: .video) { granted in<br>                cameraGranted = granted<br>                if microphoneAuthorizationStatus != .notDetermined {<br>                    checkCompletion()<br>                }<br>            }<br>        default:<br>            if microphoneAuthorizationStatus != .notDetermined {<br>                checkCompletion()<br>            }<br>        }<br>        <br>        // Handle microphone authorization<br>        switch microphoneAuthorizationStatus {<br>        case .authorized:<br>            microphoneGranted = true<br>            if cameraAuthorizationStatus != .notDetermined {<br>                checkCompletion()<br>            }<br>        case .notDetermined:<br>            AVCaptureDevice.requestAccess(for: .audio) { granted in<br>                microphoneGranted = granted<br>                if cameraAuthorizationStatus != .notDetermined {<br>                    checkCompletion()<br>                }<br>            }<br>        default:<br>            if cameraAuthorizationStatus != .notDetermined {<br>                checkCompletion()<br>            }<br>        }<br>    }<br>    <br>    private func configureCaptureDevices() {<br>        // Configure video capture device<br>        guard let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {<br>            print(&quot;Failed to get camera device&quot;)<br>            return<br>        }<br>        <br>        do {<br>            let videoInput = try AVCaptureDeviceInput(device: videoDevice)<br>            if captureSession.canAddInput(videoInput) {<br>                captureSession.addInput(videoInput)<br>            }<br>            <br>            // Configure audio capture device<br>            guard let audioDevice = AVCaptureDevice.default(for: .audio) else {<br>                print(&quot;Failed to get audio device&quot;)<br>                return<br>            }<br>            <br>            let audioInput = try AVCaptureDeviceInput(device: audioDevice)<br>            if captureSession.canAddInput(audioInput) {<br>                captureSession.addInput(audioInput)<br>            }<br>            <br>            captureDevice = videoDevice<br>            <br>        } catch {<br>            print(&quot;Error configuring capture devices: \(error)&quot;)<br>        }<br>    }<br>    <br>    private func configureVideoOutput() {<br>        // Configure video output<br>        let movieOutput = AVCaptureMovieFileOutput()<br>        <br>        // Configure stabilization if available<br>        if let connection = movieOutput.connection(with: .video) {<br>            if connection.isVideoStabilizationSupported {<br>                connection.preferredVideoStabilizationMode = .auto<br>            }<br>        }<br>        <br>        if captureSession.canAddOutput(movieOutput) {<br>            captureSession.addOutput(movieOutput)<br>            videoOutput = movieOutput<br>        }<br>    }<br>    <br>    func startRecording() {<br>        // Start the session on a background queue<br>        DispatchQueue.global(qos: .userInitiated).async {<br>            if !self.captureSession.isRunning {<br>                self.captureSession.startRunning()<br>            }<br>            <br>            // Get output file URL<br>            let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]<br>            let outputFileURL = documentsPath.appendingPathComponent(&quot;recording_\(Date().timeIntervalSince1970).mp4&quot;)<br>            <br>            // Begin recording<br>            self.videoOutput?.startRecording(to: outputFileURL, recordingDelegate: self)<br>        }<br>    }<br>    <br>    func stopRecording() {<br>        videoOutput?.stopRecording()<br>    }<br>}<br><br>// MARK: - AVCaptureFileOutputRecordingDelegate<br>extension ProfessionalMediaRecorder: AVCaptureFileOutputRecordingDelegate {<br>    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {<br>        if let error = error {<br>            print(&quot;Error recording: \(error)&quot;)<br>            return<br>        }<br>        <br>        print(&quot;Recording saved to: \(outputFileURL)&quot;)<br>        <br>        // Perform any post-processing here<br>    }<br>}</pre><h3>Advanced Recording Techniques</h3><ol><li><strong>Configuring Camera Settings</strong></li></ol><pre>func configureCameraForOptimalQuality() {<br>    guard let device = captureDevice else { return }<br>    <br>    do {<br>        try device.lockForConfiguration()<br>        <br>        // Enable auto-focus<br>        if device.isFocusModeSupported(.continuousAutoFocus) {<br>            device.focusMode = .continuousAutoFocus<br>        }<br>        <br>        // Enable auto-exposure<br>        if device.isExposureModeSupported(.continuousAutoExposure) {<br>            device.exposureMode = .continuousAutoExposure<br>        }<br>        <br>        // Set maximum frame rate<br>        device.activeVideoMinFrameDuration = CMTime(value: 1, timescale: 30)<br>        <br>        device.unlockForConfiguration()<br>    } catch {<br>        print(&quot;Error configuring camera: \(error)&quot;)<br>    }<br>}</pre><p><strong>2. Multi-Camera Recording</strong></p><pre>func setupMultiCameraRecording() {<br>    guard AVCaptureMultiCamSession.isMultiCamSupported else {<br>        print(&quot;Multi-camera recording not supported on this device&quot;)<br>        return<br>    }<br>    <br>    let multiCamSession = AVCaptureMultiCamSession()<br>}</pre><h3>3. Advanced Video Composition and Editing</h3><p>Video editing with AVFoundation offers powerful capabilities for professional-grade applications:</p><pre>import AVFoundation<br><br>class VideoCompositor {<br>    func createCompositionWithTransitions(videos: [URL], outputURL: URL, completion: @escaping (Error?) -&gt; Void) {<br>        // Create composition<br>        let composition = AVMutableComposition()<br>        <br>        // Create video track<br>        guard let videoTrack = composition.addMutableTrack(<br>            withMediaType: .video,<br>            preferredTrackID: kCMPersistentTrackID_Invalid) else {<br>            completion(NSError(domain: &quot;VideoCompositorErrorDomain&quot;, code: -1, userInfo: [NSLocalizedDescriptionKey: &quot;Could not create video track&quot;]))<br>            return<br>        }<br>        <br>        // Create audio track<br>        guard let audioTrack = composition.addMutableTrack(<br>            withMediaType: .audio,<br>            preferredTrackID: kCMPersistentTrackID_Invalid) else {<br>            completion(NSError(domain: &quot;VideoCompositorErrorDomain&quot;, code: -2, userInfo: [NSLocalizedDescriptionKey: &quot;Could not create audio track&quot;]))<br>            return<br>        }<br>        <br>        // Set up video composition for transitions<br>        let videoComposition = AVMutableVideoComposition()<br>        <br>        // Track insert time and duration<br>        var insertTime = CMTime.zero<br>        var maxWidth: CGFloat = 0<br>        var maxHeight: CGFloat = 0<br>        <br>        // Process each video asset<br>        for (index, videoURL) in videos.enumerated() {<br>            let asset = AVAsset(url: videoURL)<br>            <br>            // Get video track<br>            guard let assetVideoTrack = asset.tracks(withMediaType: .video).first else { continue }<br>            <br>            // Update max dimensions for final output<br>            let assetTrackDimensions = assetVideoTrack.naturalSize<br>            maxWidth = max(maxWidth, assetTrackDimensions.width)<br>            maxHeight = max(maxHeight, assetTrackDimensions.height)<br>            <br>            // Insert video track<br>            do {<br>                try videoTrack.insertTimeRange(<br>                    CMTimeRange(start: .zero, duration: asset.duration),<br>                    of: assetVideoTrack,<br>                    at: insertTime<br>                )<br>                <br>                // Insert audio track if available<br>                if let assetAudioTrack = asset.tracks(withMediaType: .audio).first {<br>                    try audioTrack.insertTimeRange(<br>                        CMTimeRange(start: .zero, duration: asset.duration),<br>                        of: assetAudioTrack,<br>                        at: insertTime<br>                    )<br>                }<br>                <br>                // Move insertion point forward<br>                insertTime = CMTimeAdd(insertTime, asset.duration)<br>                <br>            } catch {<br>                completion(error)<br>                return<br>            }<br>        }<br>        <br>        // Configure final video composition<br>        videoComposition.renderSize = CGSize(width: maxWidth, height: maxHeight)<br>        videoComposition.frameDuration = CMTime(value: 1, timescale: 30) // 30 fps<br>        <br>        // Add transition instructions (simplified for clarity)<br>        // In a real app, you would create proper transition layers and animations<br>        <br>        // Export the final composition<br>        guard let exportSession = AVAssetExportSession(<br>            asset: composition,<br>            presetName: AVAssetExportPresetHighestQuality) else {<br>            completion(NSError(domain: &quot;VideoCompositorErrorDomain&quot;, code: -3, userInfo: [NSLocalizedDescriptionKey: &quot;Could not create export session&quot;]))<br>            return<br>        }<br>        <br>        exportSession.outputURL = outputURL<br>        exportSession.outputFileType = .mp4<br>        exportSession.videoComposition = videoComposition<br>        exportSession.shouldOptimizeForNetworkUse = true<br>        <br>        exportSession.exportAsynchronously {<br>            switch exportSession.status {<br>            case .completed:<br>                completion(nil)<br>            case .failed:<br>                completion(exportSession.error)<br>            case .cancelled:<br>                completion(NSError(domain: &quot;VideoCompositorErrorDomain&quot;, code: -4, userInfo: [NSLocalizedDescriptionKey: &quot;Export cancelled&quot;]))<br>            default:<br>                completion(NSError(domain: &quot;VideoCompositorErrorDomain&quot;, code: -5, userInfo: [NSLocalizedDescriptionKey: &quot;Unknown export error&quot;]))<br>            }<br>        }<br>    }<br>}</pre><h3>Advanced Composition Techniques</h3><ol><li><strong>Adding Custom Transitions</strong></li></ol><pre>// Create cross-dissolve transition between clips<br>let crossDissolveInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)<br>crossDissolveInstruction.setOpacity(0.0, at: CMTimeAdd(insertTime, CMTime(seconds: -0.5, preferredTimescale: 600)))<br>crossDissolveInstruction.setOpacity(1.0, at: insertTime)</pre><p><strong>2. Adding Text Overlays</strong></p><pre>let textLayer = CATextLayer()<br>textLayer.string = &quot;Your custom text&quot;<br>textLayer.font = CTFontCreateWithName(&quot;Helvetica&quot; as CFString, 36, nil)<br>textLayer.foregroundColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1)<br>textLayer.alignmentMode = .center<br>textLayer.frame = CGRect(x: 0, y: 50, width: maxWidth, height: 50)<br><br>let videoLayer = CALayer()<br>videoLayer.frame = CGRect(x: 0, y: 0, width: maxWidth, height: maxHeight)<br><br>let parentLayer = CALayer()<br>parentLayer.frame = CGRect(x: 0, y: 0, width: maxWidth, height: maxHeight)<br>parentLayer.addSublayer(videoLayer)<br>parentLayer.addSublayer(textLayer)<br><br>videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)</pre><h3>4. Real-Time Audio Processing with AVAudioEngine</h3><p>AVAudioEngine enables sophisticated audio manipulation for professional audio applications:</p><pre>import AVFoundation<br><br>class AudioProcessor {<br>    private let audioEngine = AVAudioEngine()<br>    private let playerNode = AVAudioPlayerNode()<br>    private let pitchControl = AVAudioUnitTimePitch()<br>    private let reverbEffect = AVAudioUnitReverb()<br>    <br>    func setupAudioProcessingChain() {<br>        // Connect nodes<br>        audioEngine.attach(playerNode)<br>        audioEngine.attach(pitchControl)<br>        audioEngine.attach(reverbEffect)<br>        <br>        // Connect player -&gt; pitch effect -&gt; reverb -&gt; output<br>        audioEngine.connect(playerNode, to: pitchControl, format: nil)<br>        audioEngine.connect(pitchControl, to: reverbEffect, format: nil)<br>        audioEngine.connect(reverbEffect, to: audioEngine.mainMixerNode, format: nil)<br>        <br>        // Configure effects<br>        pitchControl.pitch = 0 // No pitch change initially<br>        reverbEffect.loadFactoryPreset(.largeHall)<br>        reverbEffect.wetDryMix = 50 // 50% effect<br>        <br>        // Prepare engine<br>        do {<br>            try audioEngine.start()<br>        } catch {<br>            print(&quot;Could not start audio engine: \(error)&quot;)<br>        }<br>    }<br>    <br>    func playAudioWithEffects(url: URL) {<br>        guard let audioFile = try? AVAudioFile(forReading: url) else {<br>            print(&quot;Could not load audio file&quot;)<br>            return<br>        }<br>        <br>        playerNode.scheduleFile(audioFile, at: nil) {<br>            print(&quot;Finished playing&quot;)<br>        }<br>        <br>        playerNode.play()<br>    }<br>    <br>    func adjustPitch(cents: Float) {<br>        pitchControl.pitch = cents<br>    }<br>    <br>    func adjustReverb(wetDryMix: Float) {<br>        reverbEffect.wetDryMix = wetDryMix<br>    }<br>}</pre><h3>Advanced Audio Techniques</h3><ol><li><strong>Real-Time Frequency Analysis</strong></li></ol><pre>func addFrequencyAnalysis() {<br>    let format = audioEngine.mainMixerNode.outputFormat(forBus: 0)<br>    audioEngine.mainMixerNode.installTap(onBus: 0, bufferSize: 1024, format: format) { buffer, time in<br>        // Process buffer data for frequency visualization<br>        let channelData = buffer.floatChannelData?[0]<br>        // Perform FFT or other analysis on channelData<br>    }<br>}</pre><p><strong>2. Voice Processing</strong></p><pre>func setupVoiceProcessing() {<br>    let voiceProcessingUnit = AVAudioUnitEQ(numberOfBands: 8)<br>    <br>    // Configure EQ bands for voice enhancement<br>    // Typical voice range: 85Hz to 255Hz (fundamental)<br>    voiceProcessingUnit.bands[0].frequency = 100<br>    voiceProcessingUnit.bands[0].gain = 3<br>    <br>    // Mid-range (presence): 2kHz to 4kHz<br>    voiceProcessingUnit.bands[3].frequency = 3000<br>    voiceProcessingUnit.bands[3].gain = 2<br>    <br>    // Add to audio chain<br>    audioEngine.attach(voiceProcessingUnit)<br>    // Connect in appropriate place in processing chain<br>}</pre><h3>5. Performance Optimization and Best Practices</h3><h3>Memory Management</h3><pre>// Release resources when no longer needed<br>func cleanupAVFoundationResources() {<br>    // Remove video observer<br>    if let timeObserverToken = timeObserverToken {<br>        player?.removeTimeObserver(timeObserverToken)<br>        self.timeObserverToken = nil<br>    }<br>    <br>    // Stop and reset playback<br>    player?.pause()<br>    player?.replaceCurrentItem(with: nil)<br>    <br>    // Remove audio engine tap if needed<br>    audioEngine.mainMixerNode.removeTap(onBus: 0)<br>    <br>    // Stop audio engine<br>    audioEngine.stop()<br>}</pre><h3>Background Processing</h3><pre>func exportVideoInBackground(composition: AVMutableComposition, outputURL: URL) {<br>    let exportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!<br>    exportSession.outputURL = outputURL<br>    exportSession.outputFileType = .mp4<br>    <br>    // Begin background task<br>    var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid<br>    backgroundTaskID = UIApplication.shared.beginBackgroundTask {<br>        UIApplication.shared.endBackgroundTask(backgroundTaskID)<br>        backgroundTaskID = .invalid<br>    }<br>    <br>    exportSession.exportAsynchronously {<br>        // End background task when export completes<br>        UIApplication.shared.endBackgroundTask(backgroundTaskID)<br>        backgroundTaskID = .invalid<br>        <br>        // Handle completion on main thread<br>        DispatchQueue.main.async {<br>            if exportSession.status == .completed {<br>                print(&quot;Export completed successfully&quot;)<br>            } else if let error = exportSession.error {<br>                print(&quot;Export failed: \(error)&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Error Handling and Debugging</h3><pre>extension AVAssetExportSession.Status: CustomStringConvertible {<br>    public var description: String {<br>        switch self {<br>        case .unknown: return &quot;unknown&quot;<br>        case .waiting: return &quot;waiting&quot;<br>        case .exporting: return &quot;exporting&quot;<br>        case .completed: return &quot;completed&quot;<br>        case .failed: return &quot;failed&quot;<br>        case .cancelled: return &quot;cancelled&quot;<br>        @unknown default: return &quot;unknown status&quot;<br>        }<br>    }<br>}<br><br>func logAVFoundationError(_ error: Error?, operation: String) {<br>    guard let error = error else { return }<br>    <br>    if let avError = error as? AVError {<br>        print(&quot;AVFoundation \(operation) error: \(avError.localizedDescription)&quot;)<br>        print(&quot;Error code: \(avError.code.rawValue)&quot;)<br>        <br>        if let failureReason = avError.userInfo[NSLocalizedFailureReasonErrorKey] as? String {<br>            print(&quot;Failure reason: \(failureReason)&quot;)<br>        }<br>        <br>        // Log additional contextual information if available<br>        if let fileSize = avError.userInfo[AVFileSize] as? Int64 {<br>            print(&quot;File size: \(ByteCountFormatter.string(fromByteCount: fileSize, countStyle: .file))&quot;)<br>        }<br>    } else {<br>        print(&quot;Non-AVFoundation error during \(operation): \(error.localizedDescription)&quot;)<br>    }<br>}</pre><h3>6. Advanced AVFoundation Applications</h3><h3>Video Filters and Effects</h3><pre>func applyVideoFilter(to asset: AVAsset, outputURL: URL, completion: @escaping (URL?) -&gt; Void) {<br>    // Create composition<br>    let composition = AVMutableComposition()<br>    guard let compositionTrack = composition.addMutableTrack(<br>        withMediaType: .video,<br>        preferredTrackID: kCMPersistentTrackID_Invalid),<br>          let assetTrack = asset.tracks(withMediaType: .video).first else {<br>        completion(nil)<br>        return<br>    }<br>    <br>    do {<br>        try compositionTrack.insertTimeRange(<br>            CMTimeRange(start: .zero, duration: asset.duration),<br>            of: assetTrack,<br>            at: .zero<br>        )<br>    } catch {<br>        print(&quot;Error creating composition: \(error)&quot;)<br>        completion(nil)<br>        return<br>    }<br>    <br>    // Create video composition<br>    let videoComposition = AVMutableVideoComposition(asset: composition) { request in<br>        let source = request.sourceImage.clampedToExtent()<br>        let filter = CIFilter(name: &quot;CIPhotoEffectNoir&quot;)!<br>        filter.setValue(source, forKey: kCIInputImageKey)<br>        <br>        // Combine with custom overlay if desired<br>        // let overlayFilter = CIFilter(name: &quot;CISourceOverCompositing&quot;)!<br>        // overlayFilter.setValue(filter.outputImage, forKey: kCIInputBackgroundImageKey)<br>        // overlayFilter.setValue(overlayImage, forKey: kCIInputImageKey)<br>        <br>        return filter.outputImage!<br>    }<br>    <br>    // Export the filtered video<br>    guard let exportSession = AVAssetExportSession(<br>        asset: composition,<br>        presetName: AVAssetExportPresetHighestQuality) else {<br>        completion(nil)<br>        return<br>    }<br>    <br>    exportSession.outputURL = outputURL<br>    exportSession.outputFileType = .mp4<br>    exportSession.videoComposition = videoComposition<br>    <br>    exportSession.exportAsynchronously {<br>        if exportSession.status == .completed {<br>            completion(outputURL)<br>        } else {<br>            print(&quot;Export failed: \(exportSession.error?.localizedDescription ?? &quot;unknown error&quot;)&quot;)<br>            completion(nil)<br>        }<br>    }<br>}</pre><h3>Live Streaming Setup</h3><pre>func setupLiveStreaming() {<br>    // Configure capture session<br>    let captureSession = AVCaptureSession()<br>    captureSession.sessionPreset = .high<br>    <br>    // Add camera input<br>    guard let camera = AVCaptureDevice.default(for: .video),<br>          let microphone = AVCaptureDevice.default(for: .audio),<br>          let videoInput = try? AVCaptureDeviceInput(device: camera),<br>          let audioInput = try? AVCaptureDeviceInput(device: microphone) else {<br>        return<br>    }<br>    <br>    if captureSession.canAddInput(videoInput) &amp;&amp; captureSession.canAddInput(audioInput) {<br>        captureSession.addInput(videoInput)<br>        captureSession.addInput(audioInput)<br>    }<br>    <br>    // Configure output<br>    let videoDataOutput = AVCaptureVideoDataOutput()<br>    videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: &quot;videoQueue&quot;))<br>    <br>    let audioDataOutput = AVCaptureAudioDataOutput()<br>    audioDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: &quot;audioQueue&quot;))<br>    <br>    if captureSession.canAddOutput(videoDataOutput) &amp;&amp; captureSession.canAddOutput(audioDataOutput) {<br>        captureSession.addOutput(videoDataOutput)<br>        captureSession.addOutput(audioDataOutput)<br>    }<br>    <br>    // Set up asset writer for HLS segments<br>    // In a real app, you would set up AVAssetWriter to write segments<br>    // and create the necessary playlist files for HLS streaming<br>    <br>    captureSession.startRunning()<br>}</pre><h3>Conclusion</h3><p>AVFoundation provides iOS developers with a robust toolkit for creating sophisticated multimedia applications. By mastering its core components, you can:</p><ul><li>Create professional-grade video players with advanced controls and capabilities</li><li>Capture high-quality audio and video with optimized settings</li><li>Compose and edit media with precision and creative control</li><li>Process audio with studio-quality effects and analysis</li><li>Deliver optimized performance even for resource-intensive operations</li></ul><p>The examples in this guide demonstrate the power and flexibility of AVFoundation, but they only scratch the surface of what’s possible. As you explore further, you’ll discover how this framework can elevate your iOS applications with rich multimedia experiences.</p><h3>Resources</h3><ul><li><a href="https://developer.apple.com/documentation/avfoundation">Apple’s AVFoundation Documentation</a></li><li><a href="https://developer.apple.com/videos/frameworks/avfoundation">WWDC Sessions on AVFoundation</a></li><li><a href="https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/00_Introduction.html">AVFoundation Programming Guide</a></li><li><a href="https://developer.apple.com/documentation/avfoundation/avspeechsynthesizer">iOS System Sounds and Haptics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bff7600104d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prevent Memory Leaks in Your SwiftUI Apps!]]></title>
            <link>https://medium.com/@muhammedyarbashk/prevent-memory-leaks-in-your-swiftui-apps-972a5ebe994f?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/972a5ebe994f</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 19:22:08 GMT</pubDate>
            <atom:updated>2025-03-08T19:22:08.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Memory leaks can severely impact the performance of your iOS app, leading to increased memory consumption, sluggish responsiveness, and even crashes. In Swift, memory leaks often occur due to <strong>retain cycles, improper handling of references, and unclosed resources</strong>. This article will help you <strong>identify, prevent, and fix memory leaks</strong> in Swift and SwiftUI applications to ensure optimal performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Z-XSkRZKsyUB3_lYsIG7DQ.png" /></figure><h3>Common Causes of Memory Leaks in SwiftUI</h3><h3>1. Unclosed Publishers &amp; Observers</h3><p>SwiftUI relies heavily on Combine for reactive programming. If you subscribe to a publisher but don’t cancel the subscription when it’s no longer needed, memory will continue to be used unnecessarily.</p><p><strong>Solution:</strong> Always use .store(in: &amp;cancellables) or manually cancel subscriptions in onDisappear or deinit.</p><pre>class ViewModel: ObservableObject {<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    init() {<br>        NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)<br>            .sink { _ in print(&quot;App became active&quot;) }<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3>2. Retain Cycles in Closures</h3><p>Using strong references inside closures can cause a retain cycle, preventing objects from being deallocated.</p><p><strong>Solution:</strong> Use [weak self] or [unowned self] when capturing self inside closures.</p><pre>class ViewModel {<br>    var fetchData: (() -&gt; Void)?<br><br>    func loadData() {<br>        fetchData = { [weak self] in<br>            self?.fetchDataFromNetwork()<br>        }<br>    }<br><br>    func fetchDataFromNetwork() {<br>        // API call logic<br>    }<br>}</pre><h3>3. Overusing @StateObject Instead of @ObservedObject</h3><p>Using @StateObject in child views unnecessarily retains the object beyond its intended lifecycle.</p><p><strong>Solution:</strong> Use @ObservedObject in child views and ensure @StateObject is used only at the top level.</p><pre>struct ParentView: View {<br>    @StateObject private var viewModel = ViewModel()<br><br>    var body: some View {<br>        ChildView(viewModel: viewModel)<br>    }<br>}<br><br>struct ChildView: View {<br>    @ObservedObject var viewModel: ViewModel<br>}</pre><h3>4. Improper Use of onAppear Without Cleanup</h3><p>Attaching expensive operations inside onAppear without cleaning them up in onDisappear can lead to excessive memory usage.</p><p><strong>Solution:</strong> Always clean up tasks when the view disappears.</p><pre>struct ContentView: View {<br>    @State private var timer: Timer?<br>    <br>    var body: some View {<br>        Text(&quot;Hello, World!&quot;)<br>            .onAppear {<br>                timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in<br>                    print(&quot;Timer running&quot;)<br>                }<br>            }<br>            .onDisappear {<br>                timer?.invalidate()<br>                timer = nil<br>            }<br>    }<br>}</pre><h3>5. Leaking EnvironmentObjects</h3><p>Using @EnvironmentObject without removing dependencies when they are no longer needed can cause unnecessary memory retention.</p><p><strong>Solution:</strong> Ensure that the object is removed or reset when no longer in use.</p><pre>struct ContentView: View {<br>    @EnvironmentObject var settings: AppSettings<br>}</pre><h3>Best Practices to Avoid Memory Leaks</h3><p>To avoid memory leaks in SwiftUI, it’s essential to follow best practices for efficient memory management. Always ensure that listeners, timers, and observers are properly invalidated and cleaned up when they are no longer needed. When using closures, prefer <strong>[weak self]</strong> to prevent retain cycles that can lead to unintended memory retention. In child views, using <strong>@ObservedObject</strong> instead of <strong>@StateObject</strong> helps prevent unnecessary object creation and improves memory efficiency. Additionally, manually removing <strong>@EnvironmentObject</strong> when it is no longer required ensures that unused objects don’t persist in memory. Lastly, using <strong>Instruments</strong> in Xcode allows you to detect and analyze memory leaks effectively, helping you optimize your SwiftUI app’s performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972a5ebe994f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Google Maps, Places, and MapKit in iOS: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@muhammedyarbashk/integrating-google-maps-places-and-mapkit-in-ios-a-step-by-step-guide-299be4f40b52?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/299be4f40b52</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 06:56:57 GMT</pubDate>
            <atom:updated>2025-03-07T06:56:57.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Integrating location-based services into your iOS app can significantly improve user experience by enabling real-time navigation, location search, and seamless interactions between users and service providers. In this guide, we’ll walk through implementing <strong>Google Maps, Google Places, and MapKit</strong> in Swift to build a fully functional mapping experience.</p><p>You’ll learn how to <strong>set up Google APIs</strong>, configure your project, and display interactive maps with features like <strong>real-time user location tracking, route navigation, and place search</strong>. Additionally, we’ll cover essential functionalities, such as <strong>displaying a user’s profile picture on the map</strong>, <strong>assigning drivers to users dynamically</strong>, and ensuring a smooth experience where the system always prioritizes the nearest available service provider.</p><p>By the end of this guide, you’ll be able to integrate robust location-based features that enhance user engagement and efficiency in your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5kUfBlbTW6v3s-rnRnMLw.png" /></figure><h3>Step 1: Enable Google APIs</h3><h3>Google Cloud Console Setup</h3><ol><li><strong>Go to Google Cloud Console</strong> → console.cloud.google.com</li><li>Create a <strong>New Project</strong></li><li>Enable the following APIs:</li></ol><ul><li><strong>Google Maps SDK for iOS</strong></li><li><strong>Places API</strong></li><li><strong>Geocoding API</strong> (if needed for address conversion)</li></ul><h3>Step 2: Install Google SDKs in Xcode</h3><h3>Using CocoaPods:</h3><p>If you are using CocoaPods, add the following dependencies in your Podfile:</p><pre>pod &#39;GoogleMaps&#39;<br>pod &#39;GooglePlaces&#39;</pre><p>Then, run:</p><pre>pod install</pre><h3>🔹 Step 3: Configure API Keys in AppDelegate</h3><p>Inside AppDelegate.swift, import the necessary modules:</p><pre>import GoogleMaps<br>import GooglePlaces<br><br>@main<br>class AppDelegate: UIResponder, UIApplicationDelegate {<br>    <br>    func application(_ application: UIApplication,<br>                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        <br>        GMSServices.provideAPIKey(&quot;YOUR_GOOGLE_MAPS_API_KEY&quot;)<br>        GMSPlacesClient.provideAPIKey(&quot;YOUR_GOOGLE_PLACES_API_KEY&quot;)<br><br>        return true<br>    }<br>}</pre><h3>🔹 Step 4: Request Location Permissions</h3><p>In <strong>Info.plist</strong>, add the following keys:</p><pre>&lt;key&gt;NSLocationWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;We need your location to show maps.&lt;/string&gt;<br>&lt;key&gt;NSLocationAlwaysUsageDescription&lt;/key&gt;<br>&lt;string&gt;We need your location for better experience.&lt;/string&gt;</pre><h3>Step 5: Implement Google Maps</h3><h3>Add a Map View in Storyboard</h3><p>Drag a UIView into your storyboard and set its class to <strong>GMSMapView</strong>.</p><h3>Display Google Map in ViewController</h3><pre>import UIKit<br>import GoogleMaps<br><br>class MapViewController: UIViewController {<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        let camera = GMSCameraPosition.camera(withLatitude: 37.7749, <br>                                              longitude: -122.4194, <br>                                              zoom: 14.0)<br><br>        let mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)<br>        self.view.addSubview(mapView)<br>    }<br>}</pre><h3>Step 6: Implement Google Places Autocomplete</h3><h3>Show a Search Bar for Places</h3><pre>import UIKit<br>import GooglePlaces<br><br>class PlacesViewController: UIViewController {<br>    <br>    let placesClient = GMSPlacesClient.shared()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>    }<br><br>    @IBAction func searchPlaceTapped(_ sender: UIButton) {<br>        let autocompleteController = GMSAutocompleteViewController()<br>        autocompleteController.delegate = self<br>        present(autocompleteController, animated: true, completion: nil)<br>    }<br>}<br><br>extension PlacesViewController: GMSAutocompleteViewControllerDelegate {<br>    <br>    func viewController(_ viewController: GMSAutocompleteViewController, <br>                        didAutocompleteWith place: GMSPlace) {<br>        print(&quot;Selected place: \(place.name ?? &quot;&quot;)&quot;)<br>        dismiss(animated: true, completion: nil)<br>    }<br><br>    func viewController(_ viewController: GMSAutocompleteViewController, <br>                        didFailAutocompleteWithError error: Error) {<br>        print(&quot;Error: \(error.localizedDescription)&quot;)<br>    }<br><br>    func wasCancelled(_ viewController: GMSAutocompleteViewController) {<br>        dismiss(animated: true, completion: nil)<br>    }<br>}</pre><h3>🔹 Step 7: Implement Apple MapKit</h3><p>If you want to support Apple Maps <strong>alongside</strong> Google Maps, use MapKit.</p><h3>Import MapKit &amp; Add Map View</h3><pre>import MapKit<br><br>class AppleMapViewController: UIViewController {<br>    <br>    var mapView: MKMapView!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        mapView = MKMapView(frame: self.view.bounds)<br>        mapView.showsUserLocation = true<br>        self.view.addSubview(mapView)<br>        <br>        // Center to user location<br>        if let userLocation = mapView.userLocation.location {<br>            let region = MKCoordinateRegion(center: userLocation.coordinate, <br>                                            latitudinalMeters: 1000, <br>                                            longitudinalMeters: 1000)<br>            mapView.setRegion(region, animated: true)<br>        }<br>    }<br>}</pre><h3>Step 8: Add Custom Markers</h3><p>For <strong>Google Maps</strong>:</p><pre>let marker = GMSMarker()<br>marker.position = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)<br>marker.title = &quot;San Francisco&quot;<br>marker.snippet = &quot;USA&quot;<br>marker.map = mapView</pre><p>For <strong>Apple Maps (MapKit)</strong>:</p><pre>let annotation = MKPointAnnotation()<br>annotation.coordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)<br>annotation.title = &quot;San Francisco&quot;<br>annotation.subtitle = &quot;USA&quot;<br>mapView.addAnnotation(annotation)</pre><h3>Step 9: Handle User Location (GPS Tracking)</h3><h3>Request Location Access</h3><p>Make sure to request permission in Info.plist (Step 4).</p><h3>Implement CLLocationManager for User Location</h3><pre>import CoreLocation<br><br>class LocationManager: NSObject, CLLocationManagerDelegate {<br>    var locationManager = CLLocationManager()<br>    <br>    override init() {<br>        super.init()<br>        locationManager.delegate = self<br>        locationManager.requestWhenInUseAuthorization()<br>        locationManager.startUpdatingLocation()<br>    }<br>    <br>    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {<br>        guard let location = locations.last else { return }<br>        print(&quot;User location: \(location.coordinate.latitude), \(location.coordinate.longitude)&quot;)<br>    }<br>}</pre><h3>Final Thoughts</h3><p>Google Maps delivers <strong>detailed, customizable maps</strong>, while the <strong>Google Places API</strong> enhances location search with <strong>autocomplete functionality</strong>. In contrast, <strong>Apple MapKit</strong> integrates seamlessly with iOS but offers <strong>fewer customization options</strong>.</p><p>The choice between <strong>Google Maps and MapKit</strong> depends on your app’s needs. If you plan to support both, consider adding a <strong>toggle option in settings</strong> to let users switch based on their preference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=299be4f40b52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Live Streaming App Using Agora SDK for iOS]]></title>
            <link>https://medium.com/@muhammedyarbashk/how-to-build-a-live-streaming-app-using-agora-sdk-for-ios-972ae22b6114?source=rss-41d1ca4f4441------2</link>
            <guid isPermaLink="false">https://medium.com/p/972ae22b6114</guid>
            <dc:creator><![CDATA[Muhammed Yarbash K]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 07:29:56 GMT</pubDate>
            <atom:updated>2025-03-07T06:05:45.791Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Developing a live streaming app comes with several challenges, including maintaining low latency, ensuring scalability, and delivering high-quality video. Agora SDK simplifies this process by providing real-time communication with ultra-low latency, a scalable cloud infrastructure, and adaptive bitrate technology that adjusts video quality based on network conditions.</p><p>Beyond live streaming, Agora also enables <strong>team meetings</strong> and <strong>one-on-one video consulting</strong>, making it a versatile solution for various communication needs. Whether it’s a virtual conference, a remote consultation, or an interactive webinar, Agora ensures seamless, high-quality video and audio experiences with built-in support for multiple participants, screen sharing, and audience engagement features.</p><h3>Bringing Live Streaming to Life with Agora SDK</h3><p>When I first set out to add <strong>live streaming</strong> to my app, I knew I needed a <strong>reliable</strong> and <strong>scalable</strong> solution. After researching multiple options, <strong>Agora SDK</strong> stood out for its ease of integration and high-quality real-time video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrqvJZ4lVjtP8Gj5JQhdiA.png" /></figure><h4>Getting Started</h4><p>I quickly created an <strong>Agora account</strong>, grabbed my <strong>App ID</strong>, and integrated the <strong>Agora SDK</strong> into my Swift app. Within minutes, I had a basic <strong>live streaming session</strong> up and running.</p><h4>The Real Challenge</h4><p>The real challenge was handling <strong>network fluctuations</strong> and ensuring smooth video quality. Thankfully, Agora’s <strong>adaptive bitrate technology</strong> automatically adjusted the stream quality based on network conditions</p><h3>Setting Up Agora SDK in Your iOS Project</h3><h3>🔹 Step 1: Create an Agora Account &amp; Get API Credentials</h3><ol><li><strong>Sign up</strong> at Agora Console</li><li><strong>Create a project</strong> → Get your <strong>App ID</strong></li><li><strong>Enable Token Authentication</strong> for better security</li><li><strong>Generate a Temporary Token</strong> (only for testing)</li></ol><h3>🔹 Step 2: Install Agora SDK in Xcode</h3><p>You can add <strong>Agora SDK</strong> using:</p><h4>➡ Swift Package Manager (SPM)</h4><ol><li>Open <strong>Xcode</strong> → <strong>File</strong> → <strong>Add Packages</strong></li><li>Enter:</li></ol><pre>https://github.com/AgoraIO/AgoraRtcEngine_iOS</pre><p>3. Click <strong>Add Package</strong></p><h4>➡ CocoaPods</h4><ol><li>Add this to your <strong>Podfile</strong>:</li></ol><pre>pod &#39;AgoraRtcKit&#39;</pre><h3>Implementing Live Streaming Features</h3><h3>🔹 Step 1: Initialize Agora Engine</h3><p>Create a helper class AgoraService.swift:</p><pre>import AgoraRtcKit<br><br>class AgoraService {<br>    var agoraKit: AgoraRtcEngineKit?<br><br>    init(appId: String, delegate: AgoraRtcEngineDelegate?) {<br>        agoraKit = AgoraRtcEngineKit.sharedEngine(withAppId: appId, delegate: delegate)<br>        agoraKit?.setChannelProfile(.liveBroadcasting)<br>    }<br><br>    func setUserRole(_ role: AgoraClientRole) {<br>        agoraKit?.setClientRole(role)<br>    }<br>}</pre><ul><li>.liveBroadcasting → Sets the app for <strong>live streaming mode</strong></li><li>.setClientRole(.broadcaster) → Makes the user a <strong>host</strong></li><li>.setClientRole(.audience) → Makes the user a <strong>viewer</strong></li></ul><h3>🔹 Step 2: Set Up Video Configuration</h3><p>Inside LiveStreamViewController.swift:</p><pre>func setupVideo() {<br>    agoraKit?.enableVideo()<br>    let videoConfig = AgoraVideoEncoderConfiguration(<br>        size: CGSize(width: 1280, height: 720),<br>        frameRate: .fps30,<br>        bitrate: AgoraVideoBitrateStandard,<br>        orientationMode: .adaptative<br>    )<br>    agoraKit?.setVideoEncoderConfiguration(videoConfig)<br>}</pre><ul><li>.enableVideo() → Enables <strong>video mode</strong></li><li>.fps30 → Sets <strong>frame rate to 30 FPS</strong></li><li>.adaptative → Automatically <strong>adjusts resolution</strong></li></ul><p>🔹 Step 3: Join a Live Channel</p><pre>func joinChannel(channelId: String, token: String, uid: UInt) {<br>    agoraKit?.joinChannel(byToken: token, channelId: channelId, info: nil, uid: uid) { (channel, uid, elapsed) in<br>        print(&quot;Joined channel: \(channel) with UID: \(uid)&quot;)<br>    }<br>}</pre><p>🔹 Step 4: Display Local Video (Host’s Camera View)</p><pre>func setupLocalVideo() {<br>    let localView = UIView(frame: self.view.bounds)<br>    self.view.addSubview(localView)<br><br>    let videoCanvas = AgoraRtcVideoCanvas()<br>    videoCanvas.uid = 0<br>    videoCanvas.view = localView<br>    videoCanvas.renderMode = .hidden<br>    agoraKit?.setupLocalVideo(videoCanvas)<br>}</pre><h3>🔹 Step 5: Render Remote Video (Audience View)</h3><pre>extension LiveStreamViewController: AgoraRtcEngineDelegate {<br>    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {<br>        let remoteView = UIView(frame: CGRect(x: 0, y: 100, width: 300, height: 400))<br>        self.view.addSubview(remoteView)<br><br>        let videoCanvas = AgoraRtcVideoCanvas()<br>        videoCanvas.uid = uid<br>        videoCanvas.view = remoteView<br>        videoCanvas.renderMode = .hidden<br>        agoraKit?.setupRemoteVideo(videoCanvas)<br>        <br>        print(&quot;Remote user joined with UID: \(uid)&quot;)<br>    }<br>}</pre><ul><li>.setupRemoteVideo(videoCanvas) → Displays <strong>other participants</strong></li></ul><h3>📌 Full Agora Live Streaming Code for iOS (Swift)</h3><pre>import UIKit<br>import AgoraRtcKit<br><br>class LiveStreamingViewController: UIViewController {<br>    <br>    // MARK: - Properties<br>    var agoraEngine: AgoraRtcEngineKit?<br>    var isVideo = true<br>    var isAudioMuted = false<br>    var isFlipCamera = false<br>    var checkTimer: Timer?<br>    <br>    // UI Elements<br>    @IBOutlet weak var remoteViewMain: UIView!<br>    @IBOutlet weak var cameraOffView: UIView!<br>    @IBOutlet weak var userIconImageView: UIImageView!<br>    @IBOutlet weak var cameraOffBtn: UIButton!<br>    @IBOutlet weak var soundeMuteBtn: UIButton!<br>    @IBOutlet weak var camerRoudeBtn: UIButton!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupAgoraEngine()<br>    }<br>    <br>    // MARK: - Setup Agora Engine<br>    func setupAgoraEngine() {<br>        let appId = &quot;YOUR_APP_ID&quot;<br>        agoraEngine = AgoraRtcEngineKit.sharedEngine(withAppId: appId, delegate: self)<br>        agoraEngine?.enableVideo()<br>    }<br>    <br>    // MARK: - Toggle Video (Mute/Unmute Camera)<br>    @objc func toggleVideo() {<br>        guard let agoraEngine = agoraEngine else { return }<br>        <br>        isVideo.toggle()<br>        agoraEngine.muteLocalVideoStream(!isVideo)<br><br>        if isVideo {<br>            // Camera is ON<br>            cameraOffView.isHidden = true<br>            userIconImageView.isHidden = true<br>            cameraOffBtn.setImage(UIImage(named: &quot;videoMuteButtonSelected&quot;), for: .normal)<br>        } else {<br>            // Camera is OFF<br>            remoteViewMain.isHidden = false<br>            cameraOffView.isHidden = false<br>            userIconImageView.isHidden = false<br>            cameraOffBtn.setImage(UIImage(named: &quot;videoMuteButton&quot;), for: .normal)<br><br>            // Ensure the grey view covers the entire area<br>            cameraOffView.frame = remoteViewMain.bounds<br>            userIconImageView.center = cameraOffView.center<br><br>            // Bring the views to front<br>            remoteViewMain.bringSubviewToFront(cameraOffView)<br>            cameraOffView.bringSubviewToFront(userIconImageView)<br>        }<br>    }<br><br>    // MARK: - Toggle Audio (Mute/Unmute Mic)<br>    @objc func toggleAudioMute() {<br>        guard let agoraEngine = agoraEngine else { return }<br>        <br>        isAudioMuted.toggle()<br>        agoraEngine.muteLocalAudioStream(isAudioMuted)<br><br>        // Update UI<br>        let buttonImage = isAudioMuted ? &quot;muteButton&quot; : &quot;muteButtonSelected&quot;<br>        soundeMuteBtn.setImage(UIImage(named: buttonImage), for: .normal)<br>    }<br><br>    // MARK: - Flip Camera (Switch Between Front &amp; Rear)<br>    @objc func flipCamera() {<br>        guard let agoraEngine = agoraEngine else { return }<br>        <br>        agoraEngine.switchCamera()<br><br>        // Update UI<br>        isFlipCamera.toggle()<br>        let buttonImage = isFlipCamera ? &quot;switchCameraButton&quot; : &quot;switchCameraButtonSelected&quot;<br>        camerRoudeBtn.setImage(UIImage(named: buttonImage), for: .normal)<br>    }<br><br>    // MARK: - Handling View Disappearance (Leaving the Channel)<br>    override func viewDidDisappear(_ animated: Bool) {<br>        super.viewDidDisappear(animated)<br>        <br>        leaveChannel()<br>        checkTimer?.invalidate() // Stop the timer when the view disappears<br>        <br>        DispatchQueue.global(qos: .userInitiated).async {<br>            DispatchQueue.main.async {<br>                AgoraRtcEngineKit.destroy()<br>            }<br>        }<br>    }<br><br>    // MARK: - Secure Token Generation (Asynchronous)<br>    func generateAgoraToken(channelName: String, uid: String, completion: @escaping (String?) -&gt; Void) {<br>        let appId = &quot;YOUR_APP_ID&quot;<br>        let appCertificate = &quot;YOUR_APP_CERTIFICATE&quot; // 🚨 NEVER expose in the app!<br>        let expireTimeInSeconds: UInt32 = 3600 // 1-hour expiry<br>        <br>        guard let url = URL(string: &quot;https://api.agora.io/v1/token&quot;) else {<br>            completion(nil)<br>            return<br>        }<br>        <br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;POST&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>        <br>        let body: [String: Any] = [<br>            &quot;app_id&quot;: appId,<br>            &quot;app_certificate&quot;: appCertificate,<br>            &quot;channel_name&quot;: channelName,<br>            &quot;uid&quot;: uid,<br>            &quot;role&quot;: &quot;publisher&quot;,<br>            &quot;expire_seconds&quot;: expireTimeInSeconds<br>        ]<br>        <br>        guard let jsonData = try? JSONSerialization.data(withJSONObject: body) else {<br>            completion(nil)<br>            return<br>        }<br>        <br>        request.httpBody = jsonData<br>        <br>        URLSession.shared.dataTask(with: request) { (data, response, error) in<br>            guard let data = data,<br>                  let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],<br>                  let authToken = json[&quot;token&quot;] as? String else {<br>                print(&quot;Error generating token: \(error?.localizedDescription ?? &quot;Unknown error&quot;)&quot;)<br>                completion(nil)<br>                return<br>            }<br>            completion(authToken)<br>        }.resume()<br>    }<br><br>    // MARK: - Joining an Agora Channel with Token<br>    func joinChannel(channelName: String, uid: UInt) {<br>        generateAgoraToken(channelName: channelName, uid: &quot;\(uid)&quot;) { token in<br>            guard let token = token else {<br>                print(&quot;Failed to fetch Agora token.&quot;)<br>                return<br>            }<br><br>            DispatchQueue.main.async {<br>                self.agoraEngine?.joinChannel(byToken: token, channelId: channelName, info: nil, uid: uid, joinSuccess: { (channel, uid, elapsed) in<br>                    print(&quot;Successfully joined channel: \(channel) with uid: \(uid)&quot;)<br>                })<br>            }<br>        }<br>    }<br><br>    // MARK: - Leaving an Agora Channel<br>    func leaveChannel() {<br>        agoraEngine?.leaveChannel(nil)<br>    }<br>}<br><br>// MARK: - Agora Delegate Implementation<br>extension LiveStreamingViewController: AgoraRtcEngineDelegate {<br>    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) {<br>        print(&quot;Joined channel: \(channel) with UID: \(uid)&quot;)<br>    }<br><br>    func rtcEngine(_ engine: AgoraRtcEngineKit, didLeaveChannelWith stats: AgoraChannelStats) {<br>        print(&quot;Left channel&quot;)<br>    }<br>}</pre><h3>Key Features of This Code</h3><p>🔹 <strong>Structured Code:</strong> Organized into clear sections.<br>🔹 <strong>Secure Token Handling:</strong> Uses a <strong>backend API</strong> to fetch tokens asynchronously.<br>🔹 <strong>Lifecycle Management:</strong> Properly <strong>destroys Agora engine</strong> on viewDidDisappear.<br>🔹 <strong>Real-Time UI Updates:</strong> Ensures <strong>buttons reflect current state</strong>.<br>🔹 <strong>Fully Functional Implementation:</strong> Covers <strong>video, audio, camera switch, and token generation</strong>.</p><h3>🔹 Summary</h3><p>This project provides a complete guide to integrating <strong>Agora SDK</strong> into an iOS app for live streaming. It covers key functionalities such as <strong>joining and leaving a live session, muting/unmuting audio and video, switching cameras, and managing real-time interactions</strong>.</p><p>The implementation includes <strong>secure token generation</strong> for authentication, ensuring a safe streaming environment. Agora’s <strong>adaptive bitrate technology</strong> optimizes video quality based on network conditions, providing a seamless experience.</p><p>Additionally, the project ensures <strong>proper resource management</strong> by handling <strong>UI updates, view lifecycle, and session cleanup</strong> when the user exits. The result is a <strong>fully functional, scalable, and high-quality live streaming app</strong> with smooth performance. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972ae22b6114" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>