<?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[iOS Nest - Medium]]></title>
        <description><![CDATA[iOS Nest, iOS geliştiricilerin deneyimlerini, teknik bilgilerini ve pratik çözümlerini paylaştığı bir topluluk yayınıdır. Swift’ten mimariye, performanstan kullanıcı deneyimine kadar iOS ekosistemine dair gerçek dünya tecrübelerini bir araya getirir. - Medium]]></description>
        <link>https://medium.com/ios-nest?source=rss----b2c468807414---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>iOS Nest - Medium</title>
            <link>https://medium.com/ios-nest?source=rss----b2c468807414---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:22:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ios-nest" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Navigasyonun Efendisi: Coordinator Pattern]]></title>
            <link>https://medium.com/ios-nest/navigasyonun-efendisi-coordinator-pattern-c0231a81508c?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/c0231a81508c</guid>
            <category><![CDATA[coordinator-pattern]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Yavuz Aytekin]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 13:42:55 GMT</pubDate>
            <atom:updated>2025-12-20T13:42:54.493Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba, güzel bir yazı ile tekrardan karşınızdayım. Bugün Coordinator Pattern’i inceleyeceğiz. Bu desen <a href="https://khanlou.com/">Soroush Khanlou</a> tarafından tanıtıldı. İlgili konuşmaya <a href="https://youtu.be/a1g3k3NObkE">şuradan</a> ulaşabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4TXZiJTxnvIx8TE5" /><figcaption>Photo by <a href="https://unsplash.com/@matthaeus123?utm_source=medium&amp;utm_medium=referral">matthaeus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Peki nedir bu Coordinator Pattern?</strong><br>Coordinator Pattern, ViewController’lar içerisindeki navigasyon işlemlerini ayrıştırarak, bu işlemleri daha sade ve yönetilebilir bir yapıya kavuşturan bir tasarım desenidir.</p><p><strong>Niçin kullanılır?</strong><br>Coordinator Pattern kullanmanın pek çok avantajı vardır. Öncelikle, navigasyon mantığını merkezi bir yere toplar, bu da kodun okunabilirliğini ve bakımını kolaylaştırır. Ayrıca, uygulamanın farklı bölümleri arasında geçiş yaparken veri iletimini daha düzenli ve esnek hale getirir. Bu desen, ayrıca test edilebilirliği de artırır çünkü bağımlılıklar ve navigasyon akışları daha açık hale gelir.</p><p>Yavaştan koda geçelim :)</p><p>Bunun için basit 3 tane ekran oluşturalım.</p><pre>final class FirstViewController: UIViewController {<br>    private let stackView: UIStackView = {<br>        let stackView = UIStackView()<br>        stackView.axis = .vertical<br>        stackView.alignment = .center<br>        stackView.spacing = 4<br>        return stackView<br>    }()<br>    <br>    private let label: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;FirstViewController&quot;<br>        return label<br>    }()<br>    <br>    private let pushSecondButton: UIButton = {<br>        let button = UIButton()<br>        button.backgroundColor = .red<br>        button.setTitle(&quot;Push Second!&quot;, for: .normal)<br>        button.addTarget(nil, action: #selector(toSecond), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br>    }<br>    <br>    func setupViews() {<br>        view.backgroundColor = .white<br>        view.addSubview(stackView)<br>        <br>        stackView.addArrangedSubview(label)<br>        stackView.addArrangedSubview(pushSecondButton)<br>        stackView.frame = CGRect(origin: .zero, size: CGSize(width: 400, height: 100))<br>        stackView.center = view.center<br>    }<br>    <br>    @objc func toSecond(_ sender: UIButton) {<br>        print(&quot;toSecond&quot;)<br>    }<br>}</pre><pre>final class SecondViewController: UIViewController {<br>    private let stackView: UIStackView = {<br>        let stackView = UIStackView()<br>        stackView.axis = .vertical<br>        stackView.alignment = .center<br>        stackView.spacing = 4<br>        return stackView<br>    }()<br>    <br>    private let label: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;SecondViewController&quot;<br>        return label<br>    }()<br>    <br>    private let presentThirdButton: UIButton = {<br>        let button = UIButton()<br>        button.backgroundColor = .red<br>        button.setTitle(&quot;Present Third!&quot;, for: .normal)<br>        button.addTarget(nil, action: #selector(toThird), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br>    }<br>    <br>    func setupViews() {<br>        view.backgroundColor = .white<br>        view.addSubview(stackView)<br>        <br>        stackView.addArrangedSubview(label)<br>        stackView.addArrangedSubview(presentThirdButton)<br>        stackView.frame = CGRect(origin: .zero, size: CGSize(width: 400, height: 100))<br>        stackView.center = view.center<br>    }<br>    <br>    @objc func toThird(_ sender: UIButton) {<br>        print(&quot;toThird&quot;)<br>    }<br>}</pre><pre>final class ThirdViewController: UIViewController {<br>    private let stackView: UIStackView = {<br>        let stackView = UIStackView()<br>        stackView.axis = .vertical<br>        stackView.alignment = .center<br>        stackView.spacing = 4<br>        return stackView<br>    }()<br>    <br>    private let label: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;ThirdViewController&quot;<br>        return label<br>    }()<br>    <br>    private let backButton: UIButton = {<br>        let button = UIButton()<br>        button.backgroundColor = .red<br>        button.setTitle(&quot;Go Back!&quot;, for: .normal)<br>        button.addTarget(nil, action: #selector(toBack), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br>    }<br>    <br>    func setupViews() {<br>        view.backgroundColor = .white<br>        view.addSubview(stackView)<br>        <br>        stackView.addArrangedSubview(label)<br>        stackView.addArrangedSubview(backButton)<br>        stackView.frame = CGRect(origin: .zero, size: CGSize(width: 400, height: 100))<br>        stackView.center = view.center<br>    }<br>    <br>    @objc func toBack(_ sender: UIButton) {<br>        print(&quot;toBack&quot;)<br>    }<br>}</pre><p>Her ViewController için Coordinator oluşturacağız. Bunun için ilk olarak protokolünü yazalım.<br>Burada ilk olarak bizim childCoordinator’ları tutmamız gerekiyor. Bunun sebebi -bu kod örneğin de yok- akış oluşturmak istediğimiz de yönetimi kolaylaştırdığındandır. <br>Sonrasında ViewControllerlar için navigationController’a ihtiyacımız var. <br>Fonksiyonlar kısmında ilk olarak start() fonksiyonu var. Coordinator’ı bu fonksiyon ile başlatıp hazır hale getireceğiz. Aynı şekilde finish() fonksiyonu ile de ViewControllerı kapatacağız. childDidFinish() fonksiyonu ile de kapanan ViewControllerın Coordinatorını sileceğiz.</p><pre>protocol Coordinator: AnyObject {<br>    var childCoordinators: [Coordinator] { get set }<br>    var navigationController: UINavigationController { get set }<br>    <br>    func start()<br>    func finish()<br>    func childDidFinish(_ child: Coordinator?)<br>}</pre><p>Sürekli yazmayalım diye childDidFinish() fonksiyonunu extensionda kullanabiliriz. finish() fonksiyonunu da opsiyonel olması adına extension içinde tanımladım.</p><pre>extension Coordinator {<br>    func finish() { }<br>    func childDidFinish(_ child: Coordinator?) {<br>        childCoordinators.removeAll(where: { $0 === child })<br>    }<br>}</pre><p>Her bir ekranımız için kendi Coordinatorını oluşturalım. Bu Coordinatorları oluştururken de dikkat etmemiz gereken bir kısım var. Normalde protokol kısmına eklemedik ancak childCoordinator olanların haliyle parentı olacak. Dolayısıyla bu coordinator içerisinde parentını tutmamız coordinatorı silerken -ve gerektiği yerde akış için- işimize yarayacak. Ayrıca parentCoordinatorı tutarken weak tutmamız retain cycle oluşmaması adına yararlı olabilir.<br>Coordinatorları oluştururken navigasyon fonksiyonlarını da ekleyelim.</p><pre>class FirstCoordinator: Coordinator {<br>    var parentCoodinator: Coordinator?<br>    <br>    var childCoordinators = [Coordinator]()<br>    var navigationController: UINavigationController<br>    <br>    init(navigationController: UINavigationController) {<br>        self.navigationController = navigationController<br>    }<br>    <br>    func start() {<br>        let vc = FirstViewController()<br>        vc.coordinator = self<br>        navigationController.pushViewController(vc, animated: true)<br>    }<br>    <br>    func pushSecond() {<br>        let child = SecondCoordinator(navigationController: navigationController)<br>        child.parentCoodinator = self<br>        childCoordinators.append(child)<br>        child.start()<br>    }<br>}</pre><pre>class SecondCoordinator: Coordinator {<br>    weak var parentCoodinator: Coordinator?<br>    <br>    var childCoordinators = [Coordinator]()<br>    var navigationController: UINavigationController<br>    <br>    init(navigationController: UINavigationController) {<br>        self.navigationController = navigationController<br>    }<br>    <br>    func start() {<br>        let vc = SecondViewController()<br>        vc.coordinator = self<br>        navigationController.pushViewController(vc, animated: true)<br>    }<br>    <br>    func finish() {<br>        parentCoodinator?.childDidFinish(self)<br>        navigationController.popViewController(animated: true)<br>    }<br>    <br>    func presentThird() {<br>        let child = ThirdCoordinator(navigationController: navigationController)<br>        childCoordinators.append(child)<br>        child.start()<br>    }<br>}</pre><pre>class ThirdCoordinator: Coordinator {<br>    weak var parentCoodinator: Coordinator?<br>    <br>    var childCoordinators = [Coordinator]()<br>    var navigationController: UINavigationController<br>    <br>    weak var viewController: UIViewController?<br>    <br>    init(navigationController: UINavigationController) {<br>        self.navigationController = navigationController<br>    }<br>    <br>    func start() {<br>        let vc = ThirdViewController()<br>        vc.coordinator = self<br>        viewController = vc<br>        navigationController.viewControllers.last?.present(vc, animated: true)<br>    }<br>    <br>    func finish() {<br>        parentCoodinator?.childDidFinish(self)<br>        viewController?.dismiss(animated: true)<br>    }<br>}</pre><p>Bu aşamada ViewControllerlara Coordinatorları ekleyelim.</p><pre>weak var coordinator: FirstCoordinator?</pre><pre>weak var coordinator: SecondCoordinator?</pre><pre>weak var coordinator: ThirdCoordinator?</pre><p>Yavaş yavaş sona yaklaşıyoruz. Bir bunları yazdık ancak uygulama başlarken de ilk ekranı çağırmamız lazım. Bunu SceneDelegate’te yapacağız.</p><pre>var coordinator: FirstCoordinator?</pre><pre>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.<br>    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.<br>    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).<br>    guard let windowScene = (scene as? UIWindowScene) else { return }<br>    let navigationController = UINavigationController()<br>    coordinator = FirstCoordinator(navigationController: navigationController)<br>    coordinator?.start()<br>    <br>    window = UIWindow(windowScene: windowScene)<br>    window?.rootViewController = navigationController<br>    window?.makeKeyAndVisible()<br>}</pre><p>Evet uygulamamız hazır. Bir çalıştırıp görelim :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*a09FFW6H7Y-nS_Mj465dIQ.gif" /></figure><p>Başarılı bir şekilde çalıştı :)</p><p>Bu yazıda, iOS uygulamalarında navigasyon işlemlerini düzenlemek ve yönetmek için Coordinator Pattern’ı nasıl kullanacağımızı inceledik. Bu desen, uygulama mimarisini temiz tutmamıza ve karmaşık navigasyon akışlarını kolayca yönetmemize olanak tanır. Coordinator Pattern’ı benimseyerek, uygulamalarımızı daha sürdürülebilir, test edilebilir ve esnek hale getirebiliriz. Bu yazı Coordinator Pattern’e giriş niteliğinde. Belki başka yazıda farklı kullanımlarına da değinebiliriz :)<br>Umarım memnun kalmışsınızdır. Daha sonra görüşmek üzere gülümsemeyle kalın 😊👋</p><p><em>İlgili kodlara </em><a href="https://github.com/yavuzaytekin/coordinator-example"><em>şuradan</em></a><em> ulaşabilirsiniz.</em></p><p><strong>Yararlandığım Kaynaklar</strong><br><a href="https://www.hackingwithswift.com/articles/71/how-to-use-the-coordinator-pattern-in-ios-apps">https://www.hackingwithswift.com/articles/71/how-to-use-the-coordinator-pattern-in-ios-apps</a><br><a href="https://khanlou.com/2015/01/the-coordinator/">https://khanlou.com/2015/01/the-coordinator/</a><br><a href="https://youtu.be/a1g3k3NObkE">https://youtu.be/a1g3k3NObkE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0231a81508c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/navigasyonun-efendisi-coordinator-pattern-c0231a81508c">Navigasyonun Efendisi: Coordinator Pattern</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[En İyi Yardımcım: Fastlane]]></title>
            <link>https://medium.com/ios-nest/en-i%CC%87yi-yard%C4%B1mc%C4%B1m-fastlane-d0701bd5b42a?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0701bd5b42a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[fastlane]]></category>
            <dc:creator><![CDATA[Yavuz Aytekin]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 13:42:34 GMT</pubDate>
            <atom:updated>2025-12-20T13:42:32.902Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba, güzel bir yazı ile tekrardan karşınızdayım. Bugün Fastlane’e küçük bir bakış atacağız. Hadi yavaştan başlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EdQXM2GgVTRc9UuL" /><figcaption>Photo by <a href="https://unsplash.com/@ekacahyadihasti?utm_source=medium&amp;utm_medium=referral">Eka Cahyadi Hasti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Fastlane nedir?</h3><p>Fastlane, uygulamaların sürümlerini ve dağıtımını otomatikleştirmek için kullanılan açık kaynak kodlu bir araçtır. Geliştiricilerin manuel süreçleri minimize ederek daha verimli çalışmasını sağlar ve hataları azaltır.</p><h4>Neler yapılabilir?</h4><p>Aslında Fastlane ile <a href="https://docs.fastlane.tools/actions/">birçok şey</a> yapılabilir. Ancak kendileri App Store için lokalize edilmiş ekran görüntüleri oluşturma, otomatik Beta ve App Store dağıtımı gibi işlemleri ön plana çıkarmaktadır.</p><p>Bunların yanında sunulan <a href="https://docs.fastlane.tools/plugins/available-plugins/">eklentiler</a> ile esnek bir yapıya da sahip.</p><h4>Kurulum</h4><p>Homebrew ile kurulumu gayet basit, tek satır ile iş bitiyor.</p><pre>brew install fastlane</pre><p>Ancak diğer kurulumlara da bakmak isterseniz <a href="https://docs.fastlane.tools/getting-started/ios/setup/">şuradan</a> ulaşabilirsiniz.</p><h4>İlk adımlar</h4><p>Fastlane’i projeye ilk defa eklerken init komutu ile temel yapılandırmayı başlatıyoruz.</p><pre>fastlane init</pre><p>Sonrasında bize aşağıdaki seçenekleri sunuyor. Tabi burada ihtiyacımıza göre ilerlememiz gerekli. Ancak daha sonra da düzenleyebileceğimiz için problem de yaşamayız. Şimdilik ben <em>Manuel Setup</em> ile ilerliyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*hlcaTg2T-0geVp84uu2cCQ.png" /></figure><p>Gerekli dökümanları oluşturuyor ve bu sırada bizi gayet güzel yönlendiriyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*xPJHaSWMfvulQ8QVB1Fdow.png" /></figure><p>Oluşturduğu dökümanları inceleyelim.<br>İlk olarak Ruby tabanlı bir araç olduğu için Gemfile oluşturmuş ve içerisinden fastlane’i çağırmış.</p><p>Fastlane klasöründe ise Appfile ve Fastfile dosyalarımız bulunuyor.</p><p>Appfile, yazacağımız otomasyon sistemde kullanacağımız bilgilerin tutulduğu dosya. İçerisinde Bundle ID, Apple ID gibi bilgileri tutabiliriz. Ancak burada önemli bir konu var, open source bir proje geliştiriyorsak direkt olarak kritik bilgileri Appfile’a koyup paylaşmamız doğru olmayabilir. Bunun için <a href="https://docs.fastlane.tools/best-practices/keys/">dotenv</a> kullanılabilir. Bu örnek kapsamında biz dotenv’yi kullanmayacağız.</p><p>Fastfile ile devam edelim. Bu dosya iş akışlarımızı -ki lane olarak adlandırılıyor- yapılandırdımız dosyadır. İçerisine ister <a href="https://docs.fastlane.tools/create-action/">kendi oluşturduğumuz</a> ister <a href="https://docs.fastlane.tools/actions/">daha önceden oluşturulmuş</a> her aksiyonu yazabiliriz. Dolayısıyla otomasyon sistemimizi burada oluştururuz.</p><p>Şimdi Fastfile dosyamızı dolduralım.</p><pre>platform :ios do<br>  desc &quot;Upload to Testflight&quot;<br>  lane :beta do<br>    apple_id = CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)<br>    app_identifier = CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier)<br>    scheme = &quot;Fastlane Demo&quot;<br><br>    scan(scheme: scheme, only_testing: [&quot;Fastlane DemoTests/Fastlane_DemoTests.swift&quot;])<br>    cert(username: apple_id)<br>    sigh(username: apple_id, app_identifier: app_identifier)<br>    increment_build_number()<br>    build(scheme: scheme)<br>    pilot(username: apple_id)<br>  end<br><br>  lane :build do |options|<br>    build_ios_app(scheme: options[:scheme])<br>  end<br>end</pre><p>Güzel, peki burada ne yaptık?</p><p>Sırasıyla;</p><ul><li>İlk olarak Appfile’dan ilgili bilgilerimizi çektik.</li><li><strong><em>scan</em></strong> aksiyonu ile belirlediğimiz şemadaki belirli testleri çalıştırdık</li><li><strong><em>cert</em></strong> ve <strong><em>sigh</em></strong> ile Apple tarafından sertifikalarımızı ve profillerimizi çektik eğer yok ise oluşturduk.</li><li><strong><em>increment_build_number</em></strong> ile projenin build numarasını arttırdık.</li><li><strong><em>build</em></strong> ile projeyi arşivleyip ipa çıkarttık.</li><li><strong><em>pilot</em></strong> ile de versiyonu Testflight’a gönderdik.</li></ul><p>Ve tüm bunları Fastlane’de daha önceden oluşturulmuş aksiyonlar ile yaptık. İşte bu kadar basit ve pratik.</p><pre>fastlane beta</pre><p>Son olarak terminalden beta lane’ini çağırdığımızda iş tamamdır. Bu kısımda demo uygulamayı TestFlight’a atmadığım için <strong><em>pilot</em></strong> aksiyonu bu şekilde hata verebilir. Ancak siz kendi uygulamanızda güvenli bir şekilde ilerleyebilirsiniz.</p><h3>Sonuç</h3><p>Fastlane, tekrarlayan işleri otomatikleştirerek zamanınızı daha verimli kullanmanızı sağlar. Bu nedenle, Fastlane’i tercih etmek, geliştirme sürecinizi önemli ölçüde kolaylaştırabilir.</p><p>Umarım memnun kalmışsınızdır. Daha sonra görüşmek üzere gülümsemeyle kalın 😊👋</p><p><em>İlgili kodlara </em><a href="https://github.com/yavuzaytekin/fastlane-demo/tree/master"><em>şuradan</em></a><em> ulaşabilirsiniz.</em></p><p><strong>Yararlandığım Kaynaklar<br></strong><a href="https://docs.fastlane.tools/">https://docs.fastlane.tools/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0701bd5b42a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/en-i%CC%87yi-yard%C4%B1mc%C4%B1m-fastlane-d0701bd5b42a">En İyi Yardımcım: Fastlane</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TipKit: Gizlimiz Kalmasın]]></title>
            <link>https://medium.com/ios-nest/tipkit-gizlimiz-kalmas%C4%B1n-86726cdf11f7?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/86726cdf11f7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[tipkit]]></category>
            <dc:creator><![CDATA[Yavuz Aytekin]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 13:41:52 GMT</pubDate>
            <atom:updated>2025-12-20T13:41:50.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba, güzel bir yazı ile tekrardan karşınızdayım. Bugün TipKit’i inceleyeceğiz. Hadi yavaştan başlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*22PCR06pqq3-52mF" /><figcaption>Photo by <a href="https://unsplash.com/@alterego_swiss?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>TipKit Nedir?</h4><p>TipKit, insanlara yeni özellikleri tanıtmayı, gizli özellikleri keşfetmelerine yardımcı olmayı kısacası uygulamanızın yararlı ipuçlarını görüntülemeyi kolaylaştıran Apple’ın framework’üdür. Bu framework ile kullanıcılarımızın tüm özellikleri bildiğinden veya haberdar olduğundan da emin olabiliriz.</p><h4>TipKit Ne Değildir?</h4><ul><li><strong>TipKit bir reklam aracı değildir</strong>: TipKit, kullanıcıları uygulama özellikleri hakkında bilgilendirmek için tasarlanmıştır. Reklam gösterme veya ürün tanıtımı yapmak için kullanılamaz. Amacı, uygulamanın işlevselliğini artırmak ve kullanıcıların deneyimini geliştirmektir, ticari amaçlarla kullanılmaz.</li><li><strong>Bir eğitim platformu değildir</strong>: TipKit, kapsamlı eğitim materyalleri sağlamak yerine, hızlı ve etkili ipuçları sunmayı amaçlar. Uzun rehberler veya karmaşık eğitim modülleri hazırlamak için uygun bir araç değildir.</li><li><strong>Teknik destek veya hata ayıklama aracı değildir</strong>: Kullanıcılara uygulamayı nasıl kullanacaklarını göstermek amacıyla tasarlanmış olsa da, TipKit kullanıcıların sorunlarını çözmek ya da uygulama hatalarını gidermek için kullanılmaz.</li></ul><p>Apple, TipKit’in kullanıcı odaklı kullanımını en verimli şekilde sağlamak için bu durumlarda kullanılmamasını öneriyor.</p><h4>TipKit Kullanımı</h4><p><strong>SwiftUI için;</strong></p><p>Öncelikle Tipleri göstermek için uygulama başlangıcında configure metodunu çağırmamız gerek. Aksi halde uygulama içerisinde Tiplerimiz gözükmez.</p><pre>@main<br>struct TipKitDemoSwiftUIApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>    <br>    init() {<br>        do {<br>            try Tips.resetDatastore()<br>            // Configure and load all tips in the app.<br>            try Tips.configure()<br>        }<br>        catch {<br>            print(&quot;Error initializing tips: \(error)&quot;)<br>        }<br>    }<br>}</pre><p>Tip protokolünü conform ederek kendi Tip’imizi oluşturalım.</p><pre>protocol FavoriteTipBluePrint: Tip { }<br><br>extension FavoriteTipBluePrint {<br>    var title: Text {<br>        Text(&quot;Save as a Favorite&quot;)<br>    }<br><br>    var message: Text? {<br>        Text(&quot;Click to button to save as a favorite.&quot;)<br>    }<br><br>    var image: Image? {<br>        Image(systemName: &quot;star&quot;)<br>    }<br>}<br><br>struct FavoriteTip: FavoriteTipBluePrint {<br>    var id: String<br>}</pre><p>Örneğimizde favori ekleme üzerinden ilerleyeceğiz. Dolayısıyla bu şekilde bir Tip şimdilik işimizi görür. İlerleyen kısımlarda biraz daha geliştirebiliriz.</p><p>Gösterim olarak iki yaklaşım mevcut. Ya inline göstermeliyiz ya da popover olarak. İkisinide yazıp karşılaştıralım.</p><pre>struct InlineView: View {<br>    let favoriteTip = FavoriteTip(id: &quot;InlineView&quot;)<br>    <br>    var body: some View {<br>        Text(&quot;Hello user&quot;)<br>        TipView(favoriteTip, arrowEdge: .bottom)<br>        Button {<br>            favoriteTip.invalidate(reason: .actionPerformed)<br>        } label: {<br>            Label(&quot;Favorite&quot;, systemImage: &quot;star&quot;)<br>        }<br>    }<br>}</pre><pre>struct PopoverView: View {<br>    let favoriteTip = FavoriteTip(id: &quot;PopoverViewTip&quot;)<br><br>    var body: some View {<br>        Text(&quot;Hello user&quot;)<br>        Button {<br>            favoriteTip.invalidate(reason: .actionPerformed)<br>        } label: {<br>            Label(&quot;Favorite&quot;, systemImage: &quot;star&quot;)<br>        }.popoverTip(favoriteTip)<br>    }<br>}</pre><p>Gördüğünüz gibi inline olanda Tip’i butonun hangi tarafında çıkmasını istiyorsak oraya yerleştirdik ve konumlandırmasını buna göre ayarladık, popover olanda ise butonu vurgulamak istediğimiz için sadece popoverTip metodunu çağırdık ve geri kalanı o bizim için halletti.<br>Burada dikkat etmemiz gereken bir konu var. Dikkat ettiyse FavoriteTip’i tanımlarken id verdik. Bunun sebebi bunlar aynı obje de olsa arka tarafta aynı yere bakıyorlar. Yani sistem id’yi kendisi atasaydı ve biz bu şekilde invalidate etseydik bu sefer birinde kapandıktan sonra diğerinde görmeyecektik.</p><p>Pekala temel görünümleri halletiyse Tip’imizin özelliklerini biraz genişletelim. Mesela aksiyon ekleyerek devam edebiliriz.</p><pre>protocol ActionFavoriteTipBluePrint: FavoriteTipBluePrint { }<br><br>struct ActionFavoriteTip: ActionFavoriteTipBluePrint {<br>    var id: String<br>    <br>    var actions: [Action] {<br>        Action(id: &quot;learn-more&quot;, title: &quot;Learn More&quot;)<br>    }<br>}</pre><p>Çağırma yapımızda bir farklılık yok. Sadece bu aksiyonu id’sinden yakalayıp ilgili aksiyonu yapmamız gerekir.</p><pre>struct ActionView: View {<br>    let favoriteTip = ExtendedFavoriteTip(id: &quot;ActionsView&quot;)<br><br>    var body: some View {<br>        Text(&quot;Hello user&quot;)<br>        Button {<br>            favoriteTip.invalidate(reason: .actionPerformed)<br>        } label: {<br>            Label(&quot;Favorite&quot;, systemImage: &quot;star&quot;)<br>        }.popoverTip(favoriteTip) { action in<br>            if action.id == &quot;learn-more&quot; {<br>                print(&quot;Go to Learn More&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>Yavaştan kural tanımlamalarına geçebiliriz. Bu tanımlamaları Rule makrosu ile yapıyoruz. Rule makrosu bizden kuralları tanımlamak için Parameter veya Event istiyor. <br>Parameter; Tip’i göstermek için tanımlayacağımız değişkenleri temsil ediyor.<br>Event; bizim takip etmek istediğimiz tekrarlanabilir aksiyonları temsil ediyor.<br>Örnek üstünde daha anlaşılır olacaktır.</p><p>Parameter tanımlaması yapılırken TipKit’in sunduğu makroyu kullanıyoruz ve bunu kural kısmına ekliyoruz. Bu parametrede her değişiklik olduğunda bizim belirlediğimiz kurala uyup uyulmadığı kontrol ediliyor ve Tip buna göre gösteriliyor veya gizleniyor.</p><pre>protocol ParameterFavoriteTipBluePrint: FavoriteTipBluePrint { }<br><br>struct ParameterFavoriteTip: ParameterFavoriteTipBluePrint {<br>    @Parameter static var isLoggedIn: Bool = false<br>    <br>    var id: String<br>    <br>    var rules: [Rule] {<br>        #Rule(Self.$isLoggedIn) {<br>            $0 == false<br>        }<br>    }<br>}</pre><pre>struct ParameterView: View {<br>    let favoriteTip = ParameterFavoriteTip(id: &quot;ParameterView&quot;)<br>    <br>    var body: some View {<br>        Text(&quot;You can save as a favorite when you are logged in&quot;)<br>        TipView(favoriteTip, arrowEdge: .bottom)<br>        Button {<br>            ParameterFavoriteTip.isLoggedIn.toggle()<br>        } label: {<br>            Label(&quot;Favorite&quot;, systemImage: &quot;star&quot;)<br>        }<br>    }<br>}</pre><p>Burada kullanıcı eğer login değil ise Tip’i göstermiyoruz. Login olduğu durumda ise gösteriliyor.</p><p>Event tanımlaması da Parameter tanımlamasına benzer. Hemen onu da halledelim.</p><pre>protocol EventFavoriteTipBluePrint: FavoriteTipBluePrint { }<br><br>struct EventFavoriteTip: EventFavoriteTipBluePrint {<br>    static let didTappedBtnEvent = Event(id: &quot;didTappedBtn&quot;)<br>    <br>    var id: String<br>    <br>    var rules: [Rule] {<br>        #Rule(Self.didTappedBtnEvent) {<br>            $0.donations.count &gt;= 3<br>        }<br>    }<br>}</pre><pre>struct EventView: View {<br>    let favoriteTip = EventFavoriteTip(id: &quot;EventView&quot;)<br>    <br>    var body: some View {<br>        Text(&quot;Hello user&quot;)<br>        TipView(favoriteTip, arrowEdge: .bottom)<br>        Button {<br>            EventFavoriteTip.didTappedBtnEvent.sendDonation()<br>        } label: {<br>            Label(&quot;Tap three times&quot;, systemImage: &quot;star&quot;)<br>        }<br>    }<br>}</pre><p>Burada kullanıcı butona üç defa basar ise Tip’i gösteriyoruz.</p><p>Event takibinde donation değerleri belirlediğimiz zaman aralığında atılmış mı diye de kontrol edebiliriz.</p><pre>#Rule(Self.didTappedBtnEvent) {<br>    $0.donations.donatedWithin(.minute).count &gt;= 3<br>}</pre><p>Burada önemli bir konu var. Belirlediğimiz zaman aralığı için en son atılan değer üstünden çıkarım yapılıyor. Yani dakikalık örneğinde ilk dakika içerisinde 2 defa tıklandı ve son tıklama 40.saniyede oldu diyelim, ikinci dakika içerisinde 40.saniyeye gelmeden 2 defa tıklanırsa Tip’i göstermiş oluruz.</p><p>Bu tarz ayarlamaları sadece Event üstünden değil direkt olarak TipOption ile Tip üstünden de yapabiliyoruz.</p><pre>protocol OptionTipBluePrint: FavoriteTipBluePrint { }<br><br>struct OptionTip: OptionTipBluePrint {<br>    <br>    var id: String<br>    <br>    var options: [Option] {<br>        MaxDisplayCount(1)<br>    }<br>}</pre><pre>struct OptionView: View {<br>    let favoriteTip = OptionFavoriteTip(id: &quot;OptionView&quot;)<br>    <br>    var body: some View {<br>        Text(&quot;Hello user&quot;)<br>        TipView(favoriteTip, arrowEdge: .bottom)<br>        Button {<br>            <br>        } label: {<br>            Label(&quot;Favorite&quot;, systemImage: &quot;star&quot;)<br>        }<br>    }<br>}</pre><p>Bu örneğimiz ilk örneklerle neredeyse aynı. Dikkat edeceğiniz gibi sadece Tip’i invalidate etmedik. İlk örneklerde butona tıklamadan veya Tip’in kapatma butonuna basmadan invalidate olmayacak ve sayfayı tekrar açmak istediğimizde tekrardan göreceğiz. Ancak OptionTip’de MaxDisplayCount’u 1 atayarak Tip’i sadece 1 kere göster demiş olduk ve invalidate etmesek dahi sayfaya tekrardan girdiğimizde görmeyeceğiz.</p><p>Peki bu Tip layoutlarını özelleştiremiyor muyuz? Evet, özelleştirebiliyoruz. Hadi birazda ona göz atalım.</p><p>Bunun için TipViewStyle protokolünden özelleşmiş layoutlarımızı türetmemiz ve daha sonrasında TipView içerisinde bu layoutu vermemiz gerekli.</p><pre>struct HeadlineTipViewStyle: TipViewStyle {<br>    func makeBody(configuration: TipViewStyle.Configuration) -&gt; some View {<br>        VStack(alignment: .leading) {<br>            HStack {<br>                Text(&quot;TIP&quot;).font(.system(.headline).smallCaps())<br>                Spacer()<br>                Button(action: { configuration.tip.invalidate(reason: .tipClosed) }) {<br>                    Image(systemName: &quot;xmark&quot;).scaledToFit()<br>                }<br>            }<br>            .padding([.top, .leading, .trailing])<br><br>            Divider().frame(height: 1.0)<br><br>            HStack(alignment: .center) {<br>                configuration.image?<br>                    .resizable()<br>                    .aspectRatio(contentMode: .fit)<br>                    .frame(width: 48.0, height: 48.0)<br><br>                VStack(alignment: .leading, spacing: 8.0) {<br>                    configuration.title?.font(.headline)<br>                    configuration.message?.font(.subheadline)<br><br>                    ForEach(configuration.actions) { action in<br>                        Button(action: action.handler) {<br>                            action.label().foregroundStyle(.blue)<br>                        }<br>                    }<br>                }<br>            }<br>            .padding(.all)<br>        }<br>    }<br>}</pre><pre>struct CustomTipStyleView: View {<br>    let favoriteTip = FavoriteTip(id: &quot;CustomTipStyleView&quot;)<br>    <br>    var body: some View {<br>        Text(&quot;Hello user&quot;)<br>        TipView(favoriteTip, arrowEdge: .bottom)<br>            .tipViewStyle(HeadlineTipViewStyle())<br>        Button {<br>            favoriteTip.invalidate(reason: .actionPerformed)<br>        } label: {<br>            Label(&quot;Favorite&quot;, systemImage: &quot;star&quot;)<br>        }<br>    }<br>}</pre><p>Bu kullanım ile standart olanından çıkmış oluyoruz.</p><p>SwiftUI’da nasıl kullanıldığından bahsettik. Birazda UIKit tarafına bakalım.</p><p><strong>UIKit için;</strong></p><p>Tiplerin oluşturulma kısımları zaten aynı. Kullanım kısımları için ise Apple’ın sunduğu destekler mevcut.</p><p>InlineView olarak şu şekilde yazabiliriz.</p><pre>class InlineViewController: UIViewController {<br>    lazy var mainStackView: UIStackView = {<br>        let stackView = UIStackView(arrangedSubviews: [helloUserLabel, favoriteBtn])<br>        stackView.axis = .vertical<br>        stackView.alignment = .center<br>        stackView.distribution = .equalCentering<br>        stackView.spacing = 4<br>        return stackView<br>    }()<br>    <br>    lazy var helloUserLabel: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;Hello user&quot;<br>        label.textColor = .black<br>        return label<br>    }()<br>    <br>    lazy var favoriteBtn: UIButton = {<br>        let button = UIButton(type: .custom)<br>        button.setTitle(&quot;Favorite&quot;, for: .normal)<br>        button.setImage(.init(systemName: &quot;star&quot;), for: .normal)<br>        button.setTitleColor(.systemBlue, for: .normal)<br>        button.addTarget(self, action: #selector(favoriteBtnAction), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    lazy var tipView: TipUIView = {<br>        let view = TipUIView(favoriteTip)<br>        view.translatesAutoresizingMaskIntoConstraints = false<br>        return view<br>    }()<br>    <br>    private var tipObservationTask: Task&lt;Void, Never&gt;?<br>    private var favoriteTip = FavoriteTip(id: &quot;InlineView&quot;)<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .white<br>        configure()<br>    }<br>    <br>    override func viewDidAppear(_ animated: Bool) {<br>        super.viewDidAppear(animated)<br>        showFavoriteTipIfNeeded()<br>    }<br>    <br>   override func viewWillDisappear(_ animated: Bool) {<br>       super.viewWillDisappear(animated)<br><br>       tipObservationTask?.cancel()<br>       tipObservationTask = nil<br>   }<br>    <br>    func configure() {<br>        mainStackView.translatesAutoresizingMaskIntoConstraints = false<br>        view.addSubview(mainStackView)<br>        view.addConstraints([<br>            mainStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>            mainStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>            mainStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)<br>        ])<br>    }<br>    <br>    func showFavoriteTipIfNeeded() {<br>        tipObservationTask = tipObservationTask ?? Task { @MainActor in<br>            for await shouldDisplay in favoriteTip.shouldDisplayUpdates {<br>                if shouldDisplay {<br>                    mainStackView.insertArrangedSubview(tipView, at: 1)<br>                } else {<br>                    tipView.removeFromSuperview()<br>                }<br>            }<br>        }<br>    }<br><br>    @objc func favoriteBtnAction() {<br>        favoriteTip.invalidate(reason: .actionPerformed)<br>    }<br>}</pre><p>Inline olarak yazmak istediğimizde TipUIView kullanabiliriz. Tabi ki bunu view’a ekleyip yönetmemiz gerekir. <br>Bunun yanında burada dikkat etmemiz gereken bir konu var. Tip’i göstermek istiyorsak bu fonksiyonu en erken viewDidAppear’da çağırmamız gerek. Onun dışında <em>shouldDisplayUpdates </em>ile Tip’i göstermemiz gerekiyor mu bunu kontrol etmemiz gerek. Bu durumlar popover içinde geçerli.</p><p>Şimdi PopoverView olarak nasıl gösterebiliriz ona bakalım.</p><pre>class PopoverViewController: UIViewController {<br>    lazy var mainStackView: UIStackView = {<br>        let stackView = UIStackView(arrangedSubviews: [helloUserLabel, favoriteBtn])<br>        stackView.axis = .vertical<br>        stackView.alignment = .center<br>        stackView.distribution = .equalCentering<br>        stackView.spacing = 4<br>        return stackView<br>    }()<br>    <br>    lazy var helloUserLabel: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;Hello user&quot;<br>        label.textColor = .black<br>        return label<br>    }()<br>    <br>    lazy var favoriteBtn: UIButton = {<br>        let button = UIButton(type: .custom)<br>        button.setTitle(&quot;Favorite&quot;, for: .normal)<br>        button.setImage(.init(systemName: &quot;star&quot;), for: .normal)<br>        button.setTitleColor(.systemBlue, for: .normal)<br>        button.addTarget(self, action: #selector(favoriteBtnAction), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    lazy var tipPopoverController: TipUIPopoverViewController = {<br>        let popoverController = TipUIPopoverViewController(favoriteTip, sourceItem: favoriteBtn)<br>        return popoverController<br>    }()<br>    <br>    private var tipObservationTask: Task&lt;Void, Never&gt;?<br>    private var favoriteTip = FavoriteTip(id: &quot;PopoverView&quot;)<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .white<br>        configure()<br>    }<br>    <br>    override func viewDidAppear(_ animated: Bool) {<br>        super.viewDidAppear(animated)<br>        showFavoriteTipIfNeeded()<br>    }<br>    <br>   override func viewWillDisappear(_ animated: Bool) {<br>       super.viewWillDisappear(animated)<br><br>       tipObservationTask?.cancel()<br>       tipObservationTask = nil<br>   }<br>    <br>    func configure() {<br>        mainStackView.translatesAutoresizingMaskIntoConstraints = false<br>        view.addSubview(mainStackView)<br>        view.addConstraints([<br>            mainStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>            mainStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>            mainStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)<br>        ])<br>    }<br>    <br>    func showFavoriteTipIfNeeded() {<br>        tipObservationTask = tipObservationTask ?? Task { @MainActor in<br>            for await shouldDisplay in favoriteTip.shouldDisplayUpdates {<br>                if shouldDisplay {<br>                    present(tipPopoverController, animated: true)<br>                } else {<br>                    if presentedViewController is TipUIPopoverViewController {<br>                        dismiss(animated: true)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    @objc func favoriteBtnAction() {<br>        favoriteTip.invalidate(reason: .actionPerformed)<br>    }<br>}</pre><p>Popover olarak göstermek istediğimiz TipUIPopoverViewController kullanmamız gerek.</p><h4>Sonuç</h4><p>Apple’ın <strong>TipKit</strong> framework’ü, geliştiricilere uygulama deneyimini bir adım ileri taşıma fırsatı sunuyor. İster yeni özellikler tanıtın ister mevcut özellikleri daha iyi açıklayın, TipKit ile kullanıcılarınızın deneyimini iyileştirmek artık çok daha kolay.</p><p>Umarım memnun kalmışsınızdır. Daha sonra görüşmek üzere gülümsemeyle kalın 😊👋</p><p><em>İlgili kodlara </em><a href="https://github.com/yavuzaytekin/TipKitDemo"><em>şuradan</em></a><em> ulaşabilirsiniz.</em></p><p><strong>Yararlandığım Kaynaklar<br></strong><a href="https://developer.apple.com/documentation/tipkit">https://developer.apple.com/documentation/tipkit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86726cdf11f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/tipkit-gizlimiz-kalmas%C4%B1n-86726cdf11f7">TipKit: Gizlimiz Kalmasın</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS’ta Zero Copy: Ufak Bir Bakış]]></title>
            <link>https://medium.com/ios-nest/iosta-zero-copy-ufak-bir-bak%C4%B1%C5%9F-a51472990c62?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/a51472990c62</guid>
            <category><![CDATA[zero-copy]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Yavuz Aytekin]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 13:41:35 GMT</pubDate>
            <atom:updated>2025-12-20T13:41:18.447Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba, güzel bir yazı ile tekrardan karşınızdayım. Bugün Zero Copy’e ufaktan bir değineceğiz. Hadi yavaştan başlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SQYLsnJcSKyPmBPJ" /><figcaption>Photo by <a href="https://unsplash.com/@ageing_better?utm_source=medium&amp;utm_medium=referral">Centre for Ageing Better</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Zero Copy nedir?</strong></h4><p>Zero copy, verinin bellekte <strong>yeni bir kopyasını oluşturmadan</strong> işlenmesini sağlayan bir yöntemdir.</p><p>Normalde bir dosyayı, string’i veya byte dizisini işlediğimizde sistem bunu RAM’e kopyalar. Bu hem CPU maliyetlidir hem de büyük veri için bellek baskısı oluşturur.</p><p>Zero copy teknikleri sayesinde CPU daha az yorulur, bellek kullanımınız düşer, büyük veriyle çalışırken uygulama daha akıcı kalır.</p><p>iOS’ta bunu sağlayan yöntemlerden bazıları:</p><ul><li>Data(contentsOf:, options: .mappedIfSafe) -&gt;Memory mapped file</li><li>Substring -&gt; Veri kopyalamayan string slice</li><li>UnsafeBufferPointer -&gt;Buffer referans paylaşımı</li><li>Metal / AVFoundation buffer referansları</li></ul><p>Bu yazıda memory mapping ve Substring tabanlı parsing’i konu alan basit iki örnek üstünden ilerleyeceğiz.</p><h4>Örnek 1: Memory Mapped Dosya Okuma</h4><p>Basit bir dosya yükleme ile ilgili örnek yapalım. Örneğimizde lokaldeki bir görselin datasını alıp UIImage’e döndüreceğiz ve bunu yaparken bir normal yoldan bir de zero copy kullanarak yapıp aralarındaki süre farkını kontrol edeceğiz. Burada sadece dosya okuma maliyetini ölçüyoruz, decode maliyeti sabit kalıyor.</p><pre>    @IBAction func loadImageTraditional(_ sender: Any) {<br>        guard let url = Bundle.main.url(/service/forresource: &quot;lion&quot;, withExtension: &quot;jpg&quot;) else { return }<br>        let start = CFAbsoluteTimeGetCurrent()<br>        do {<br>            let data = try Data(contentsOf: url)<br>            let image = UIImage(data: data)<br>            print(&quot;✅ Traditional Image Size: \(String(describing: image?.size))&quot;)<br>        } catch {<br>            print(&quot;❌ Traditional load failed: \(error)&quot;)<br>        }<br>        let end = CFAbsoluteTimeGetCurrent()<br>        print(&quot;⏱️ Traditional Load Time: \(end - start) sec&quot;)<br>    }</pre><p>Bu yöntemde Data(contentsOf:) dosyayı RAM’e tam olarak kopyalar. Bu yaklaşım basittir ancak özellikle büyük dosyalarda gereksiz bir memory kopyası yaratır.</p><pre>    @IBAction func loadImageZeroCopy(_ sender: Any) {<br>        guard let url = Bundle.main.url(/service/forresource: &quot;lion&quot;, withExtension: &quot;jpg&quot;) else { return }<br>        let start = CFAbsoluteTimeGetCurrent()<br>        do {<br>            let data = try Data(contentsOf: url, options: .mappedIfSafe)<br>            let image = UIImage(data: data)<br>            print(&quot;✅ Mapped Image Size: \(String(describing: image?.size))&quot;)<br>        } catch {<br>            print(&quot;❌ MappedIfSafe failed: \(error)&quot;)<br>        }<br>        let end = CFAbsoluteTimeGetCurrent()<br>        print(&quot;⏱️ Mapped Load Time: \(end - start) sec&quot;)<br>    }</pre><p>.mappedIfSafe seçeneği ise iOS’a “Bu dosyayı memory map edebiliyorsan et” der ve bu yöntemde çoğu zaman dosya RAM’e kopyalanmaz. iOS, dosyayı <strong>mmap</strong> ile belleğe haritalar ve data bu haritayı direkt referans alır. Bu örnekte UIImage(data:) çağrısı JPG’yi decode ettiği için yeni bir pixel buffer oluşturur, yani decode kısmı zero-copy değildir.<br>Ancak <strong>dosyayı okuma aşaması</strong> memory mapped olduğu için kopyasız gerçekleşir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*U_QnPKhtXbNeD9BPtYD6QA.png" /></figure><p>Bu görselde de aradaki süre farkını görebiliriz.</p><h4>Örnek 2: Streaming Text Parse</h4><p>Şimdi başka bir örneği daha inceleyelim. Bu örnekte mock streaming oluşturacağız. Her 2 saniyede bir gelen JSON satırını alıp Substring ile parse edeceğiz. Substringler, orjinal String ile aynı memory bölgesini paylaştığı için kopya oluşturmaz ve bu da zero copy kapsamına girer.</p><pre>class ChatViewModel: ObservableObject {<br>    @Published var messages: [Message] = []<br><br>    private let fakeStream: [String] = [<br>        &quot;{\&quot;user\&quot;:\&quot;Alice\&quot;,\&quot;text\&quot;:\&quot;Hello everyone!\&quot;}&quot;,<br>        &quot;{\&quot;user\&quot;:\&quot;Bob\&quot;,\&quot;text\&quot;:\&quot;Great talk!\&quot;}&quot;,<br>        &quot;{\&quot;user\&quot;:\&quot;Charlie\&quot;,\&quot;text\&quot;:\&quot;Amazing content!\&quot;}&quot;,<br>        &quot;{\&quot;user\&quot;:\&quot;Denise\&quot;,\&quot;text\&quot;:\&quot;Zero-copy is cool!\&quot;}&quot;<br>    ]<br><br>    private var index = 0<br>    private var timer: Timer?<br><br>    func startStreaming() {<br>        timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { _ in<br>            guard self.index &lt; self.fakeStream.count else {<br>                self.timer?.invalidate()<br>                return<br>            }<br><br>            let line = self.fakeStream[self.index]<br>            self.index += 1<br><br>            let slice = line[...]<br>            let tokens = tokenize(slice)<br><br>            if let user = tokens.first(where: { $0.key == &quot;user&quot; })?.value,<br>               let text = tokens.first(where: { $0.key == &quot;text&quot; })?.value {<br>                let message = Message(user: user, text: text)<br>                DispatchQueue.main.async {<br>                    self.messages.append(message)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Burada startStreaming metodu ile mock streamingi başlatıyoruz. Metod içindeki line[...] ile yeni bir dinamik string üretmek yerine slice oluşturuyoruz. Bu işlem aslında memory paylaşan bir Substring üretir.</p><p>Json parse işlemini string kopyalamadan yaptığımız için gelen stream verisi ne kadar büyük olursa olsun, memory footprint <strong>sabit</strong> kalır.</p><pre>struct JSONToken {<br>    let key: Substring<br>    let value: Substring<br>}<br><br>func tokenize(_ line: Substring) -&gt; [JSONToken] {<br>    var tokens: [JSONToken] = []<br>    var scanner = line<br><br>    while let keyStart = scanner.firstIndex(of: &quot;\&quot;&quot;),<br>          let keyEnd = scanner[keyStart...].dropFirst().firstIndex(of: &quot;\&quot;&quot;) {<br><br>        let key = scanner[scanner.index(after: keyStart)..&lt;keyEnd]<br>        guard let colon = scanner[keyEnd...].firstIndex(of: &quot;:&quot;) else { break }<br><br>        scanner = scanner[scanner.index(after: colon)...]<br><br>        if scanner.first == &quot;\&quot;&quot; {<br>            guard let valueEnd = scanner.dropFirst().firstIndex(of: &quot;\&quot;&quot;) else { break }<br>            let value = scanner[scanner.index(after: scanner.startIndex)..&lt;valueEnd]<br>            tokens.append(.init(key: key, value: value))<br>            scanner = scanner[scanner.index(after: valueEnd)...]<br>        } else {<br>            break<br>        }<br><br>        if let comma = scanner.firstIndex(of: &quot;,&quot;) {<br>            scanner = scanner[scanner.index(after: comma)...]<br>        }<br>    }<br><br>    return tokens<br>}</pre><p>Bu da yazmış olduğumuz parser, bu parser <strong>hiçbir yerde yeni String oluşturmaz</strong>. Her key ve value bir Substring’dir ve streaming verisinin tamamı büyüse bile memory footprint değişmez.</p><h3>Sonuç</h3><p>Zero-copy teknikleri:</p><ul><li>streaming</li><li>büyük JSON parse</li><li>dosya okuma</li><li>medya işleme</li><li>frame buffer işleme</li></ul><p>gibi alanlarda çok ciddi kazanç sağlar.</p><p>iOS zaten çoğu yerde optimize davranır, evet. Ancak <strong>kopyalamayı tamamen ortadan kaldırmak sizin elinizde</strong>.</p><p>Umarım memnun kalmışsınızdır. Daha sonra görüşmek üzere gülümsemeyle kalın 😊👋</p><p><em>İlgili kodlara </em><a href="https://github.com/yavuzaytekin/Zero-Copy-Demo.git"><em>şuradan</em></a><em> ulaşabilirsiniz.</em></p><p><strong>Yararlandığım Kaynaklar<br></strong><a href="https://developer.apple.com/documentation">https://developer.apple.com/documentation</a><br><a href="https://developer.apple.com/documentation/foundation/nsdata/readingoptions/mappedifsafe">https://developer.apple.com/documentation/foundation/nsdata/readingoptions/mappedifsafe</a><br><a href="https://developer.apple.com/documentation/swift/substring">https://developer.apple.com/documentation/swift/substring</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51472990c62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/iosta-zero-copy-ufak-bir-bak%C4%B1%C5%9F-a51472990c62">iOS’ta Zero Copy: Ufak Bir Bakış</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC ile Basit Sesli Sohbet Uygulaması]]></title>
            <link>https://medium.com/ios-nest/webrtc-ile-basit-sesli-sohbet-uygulamas%C4%B1-4a445328de2?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/4a445328de2</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Yavuz Aytekin]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 13:40:46 GMT</pubDate>
            <atom:updated>2025-12-20T13:40:44.983Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar, bu yazıda iOS için WebRTC ile basit sesli sohbet uygulaması geliştirdim. Basit olması sebebiyle çok fazla detaya inmeden olabildiğince sade anlatmak istedim. Sizleri terimlerle boğmak ve de sıkmak istemedim. Keyifli okumalar dilerim. Hadi başlayalım :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*DogjpBkAajcNz9-g3Gk3hQ.png" /></figure><p><strong>WebRTC nedir?</strong><br>Aslında WebRTC kısaltma ismi. Uzun ismi Web Real Time Communication. Tarayıcıların ve mobil uygulamaların gerçek zamanlı iletişim kurmalarına olanak sağlayan açık kaynak ve ücretsiz bir projedir. Bu proje sayesinde eşten eşe (p2p) bağlantı sağlayarak görüntülü veya sesli iletişim kurabiliyoruz. Diğer data türlerini de gönderebiliyoruz. Ancak daha çok görüntü ve ses ön plana çıkıyor.</p><p>Zamanında Google’ın satın aldığı Global IP Solutions tarafından geliştirildi. Sonrasında Google’ın vermiş olduğu karar ile açık kaynak olarak yayınlandı.</p><p><strong>Nasıl Çalışır?</strong><br>Kullanıcılar birbirlerine adreslerini ve nasıl iletişim sağlamak istediklerini (görüntülü — sesli) gönderirler. Tabi ne kadar eşten eşe bir bağlantı olmasını istiyorsakta bu aşamada sunucu kullanmamız gerekiyor. Bu iletişim adreslerinin paylaşıldığı kısım Signaling olarak adlandırılıyor. Genelde sinyalleşme web apilerle veya websocketle çözülüyor. Bağlantı sağlandıktan sonra WebRTC devreye giriyor.</p><p><em>Başlamadan önce şunu söylemem gerek, M80 versiyonundan sonra Android ve iOS precompiled dağıtımı için devam etmeme kararı alınmış. İlgili notlara </em><a href="https://groups.google.com/g/discuss-webrtc/c/Ozvbd0p7Q1Y/m/M4WN2cRKCwAJ?pli=1"><strong><em>şuradan</em></strong></a><em> ulaşabilirsiniz. Bu nedenle biz derlemeyle uğraşmamak adına GitHub’ta bulunan resmi olmayan ama güncel kalmaya çalışan </em><a href="https://github.com/stasel/WebRTC"><em>şu paketi</em></a><em> kullanacağız. Yavaştan koda geçelim :)</em></p><p>İlk olarak bağlantıyı sağlamak adına kullanıcıların adreslerini paylaşmamız gerek. Bunun için webSocket kullanacağız. Ben Starscream paketini ekledim. Hızlıdan bir SocketClient yazalım.</p><pre>enum SocketStatus {<br>    case connected<br>    case disconnected<br>}</pre><pre>protocol SocketClientDelegate: AnyObject {<br>    func changedSocketStatus(with status: SocketStatus)<br>    func handleSocketData(with data: Data)<br>}<br><br>protocol SocketClientProtocol {<br>    var delegate: SocketClientDelegate? { get set }<br>}<br><br>class SocketClient: SocketClientProtocol {<br>    weak var delegate: SocketClientDelegate?<br>    private var socket: WebSocket?<br>    <br>    init() {<br>        var request = URLRequest(url: URL(string: &quot;http://localhost:8080&quot;)!)<br>        request.timeoutInterval = 5<br>        socket = WebSocket(request: request)<br>        socket?.delegate = self<br>        socket?.connect()<br>    }<br>}<br><br>extension SocketClient: WebSocketDelegate {<br>    func didReceive(event: WebSocketEvent, client: WebSocket) {<br>        switch event {<br>        case .connected(let headers):<br>            debugPrint(&quot;websocket is connected: \(headers)&quot;)<br>            delegate?.changedSocketStatus(with: .connected)<br>        case .disconnected(let reason, let code):<br>            debugPrint(&quot;websocket is disconnected: \(reason) with code: \(code)&quot;)<br>            delegate?.changedSocketStatus(with: .disconnected)<br>        case .binary(let data):<br>            debugPrint(&quot;Received data: \(data.count)&quot;)<br>            delegate?.handleSocketData(with: data)<br>        default:<br>            print(&quot;Received data&quot;)<br>        }<br>    }<br>}</pre><p>Bu SocketClient için bir de sunucuya ihtiyacımız var. Hemen hızlıdan onu da yazalım. Node.js ile hızlı bir çözüm yapalım.</p><pre>const WebSocket = require(&quot;ws&quot;);<br><br>const wss = new WebSocket.Server({ port: 8080 }, () =&gt; {<br>  console.log(&quot;Signaling server is now listening on port 8080&quot;);<br>});<br><br>wss.broadcast = (ws, data) =&gt; {<br>  wss.clients.forEach((client) =&gt; {<br>    if (client !== ws &amp;&amp; client.readyState === WebSocket.OPEN) {<br>      client.send(data);<br>    }<br>  });<br>};<br><br>wss.on(&quot;connection&quot;, (ws) =&gt; {<br>  console.log(`Client connected. Total connected clients: ${wss.clients.size}`);<br><br>  ws.onmessage = (message) =&gt; {<br>    console.log(message.data + &quot;\n&quot;);<br>    wss.broadcast(ws, message.data);<br>  };<br><br>  ws.onclose = () =&gt; {<br>    console.log(<br>      `Client disconnected. Total connected clients: ${wss.clients.size}`<br>    );<br>  };<br>});</pre><p>Şimdi ViewController’a soketi ve ihtiyacımız olan UI komponentlerini ekleyelim. Ardından sunucuyu başlatıp bağlanalım.</p><pre>class ViewController: UIViewController {<br>    @IBOutlet weak var socketStatusLabel: UILabel!<br>    @IBOutlet weak var localSDPLabel: UILabel!<br>    @IBOutlet weak var remoteSDPLabel: UILabel!<br>    <br>    var socket: SocketClientProtocol?<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        configureSocket()<br>    }<br>    <br>    func configureSocket() {<br>        socket = SocketClient()<br>        socket?.delegate = self<br>    }<br>    <br>    @IBAction func sendOffer(_ sender: Any) {<br>        debugPrint(&quot;sendOffer&quot;)<br>    }<br>    <br>    @IBAction func sendAnswer(_ sender: Any) {<br>        debugPrint(&quot;sendAnswer&quot;)<br>    }<br>    <br>    private func changeSocketStatus(with status: SocketStatus) {<br>        var socketStatusText = &quot;Socket Status: &quot;<br>        switch status {<br>        case .connected:<br>            socketStatusText.append(&quot;🟢&quot;)<br>        case .disconnected:<br>            socketStatusText.append(&quot;🔴&quot;)<br>        }<br>        DispatchQueue.main.async {<br>            self.socketStatusLabel.text = socketStatusText<br>        }<br>    }<br>}<br><br>// MARK: - SocketClientDelegate<br>extension ViewController: SocketClientDelegate {<br>    func changedSocketStatus(with status: SocketStatus) {<br>        changeSocketStatus(with: status)<br>    }<br>    <br>    func handleSocketData(with data: Data) {<br>        //TODO: implement<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*AZ-nTHMjq5u5wqfO0bd_Sw.png" /><figcaption>Başlangıç</figcaption></figure><p>Soketi başarılı şekilde bağladıktan sonra yavaştan WebRTCClient’ı yazmaya başlayalım.<br>Bunun için ilk olarak <strong><em>RTCPeerConnection</em></strong>’a ihtiyacımız var.</p><pre>private var peerConnection: RTCPeerConnection</pre><p><em>RTCPeerConnection; biz ve bağlantı kuracağımız kişi/ler arasındaki bağlantıyı temsil eder. Bu arayüz sayesinde karşı taraf ile bağlantı kurabiliriz, kurulan bağlantıyı yönetebilir, görüntüleyebilir veya kapatabiliriz.<br> </em><br>RTCPeerConnection&#39;ı üretmek için RTCPeerConnectionFactory&#39;e ihtiyacımız var. Ancak bunu <em>static</em> tanımlamamız gerekli aksi halde uygulamamız hata verebilir.</p><pre>private static let factory: RTCPeerConnectionFactory = {<br>    return RTCPeerConnectionFactory()<br>}()</pre><p><em>Bu aşamada şunu söylemem gerek, biz sesli sohbet uygulaması geliştirdiğimiz için görüntülü sohbet için gerekli kısımları eklemiyoruz. Dolayısıyla bu aşamalarda videoEncoder ve videoDecoder da eklenebilir.</em></p><p>RTCPeerConnectionDelegate’ini de WebRTCClient’a entegre edelim.<br><em>Bu aşamada WebRTCClient’ı RTCPeerConnectionDelegate’i sebebiyle NSObjectten türetmemiz gerekiyor.</em></p><pre>extension WebRTCClient: RTCPeerConnectionDelegate {<br>    func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {<br>        debugPrint(&quot;WebRTCClient didChange stateChanged: \(stateChanged)&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {<br>        debugPrint(&quot;WebRTCClient didAdd stream: \(stream)&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {<br>        debugPrint(&quot;WebRTCClient didRemove stream: \(stream)&quot;)<br>    }<br>    <br>    func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {<br>        debugPrint(&quot;WebRTCClient peerConnectionShouldNegotiate&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {<br>        debugPrint(&quot;WebRTCClient didChange newState: \(newState)&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {<br>        debugPrint(&quot;WebRTCClient didChange newState: \(newState)&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {<br>        debugPrint(&quot;WebRTCClient didGenerate candidate: \(candidate)&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {<br>        debugPrint(&quot;WebRTCClient didRemove candidates: \(candidates)&quot;)<br>    }<br>    <br>    func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {<br>        debugPrint(&quot;WebRTCClient didOpen dataChannel: \(dataChannel)&quot;)<br>    }<br>}</pre><p>Yavaş yavaş kodumuz olgunlaşmaya başladı.<br>Şimdi bizim medya tarafını eklememiz gerekiyor. Biz sesli sohbet uygulaması yapacağımız için sadece audioTrack eklememiz yeterli olacaktır.</p><pre>private func addAudioTrack() {<br>    let streamId = &quot;audioStream&quot;<br>    let audioTrack = createAudioTrack()<br>    peerConnection?.add(audioTrack, streamIds: [streamId])<br>}<br><br>private func createAudioTrack() -&gt; RTCAudioTrack {<br>    let audioTrack = WebRTCClient.factory.audioTrack(withTrackId: &quot;audio&quot;)<br>    return audioTrack<br>}</pre><p>Ses kısmını yöneteceğimiz AudioSession‘ı da yapılandırmamız gerekli. AudioSession paylaşımlı bir obje olduğu için araya başka isteğin girmemesi adına ilk önce kilitlemememiz ardından ilgili yapılandırmaları yapıp tekrardan açmamız gerekiyor.</p><p><em>Ayrıca AudioSession’ı yapılandırmak isteyip bu kilitleme işlemini yapmadığımız takdirde uygulamamız hata verecektir.</em></p><pre>private func configureAudioSession() {<br>    rtcAudioSession.lockForConfiguration()<br>    try! rtcAudioSession.setCategory(AVAudioSession.Category.playAndRecord.rawValue)<br>    try! rtcAudioSession.setMode(AVAudioSession.Mode.voiceChat.rawValue)<br>    rtcAudioSession.unlockForConfiguration()<br>}</pre><p>Şimdi önemli bir kısma geldik. İstek gönderme ve cevap verme fonksiyonlarını yazacağız. İlgili PeerConnection üstünden <em>offer</em> ve <em>answer</em> metodlarını çağıracağız. Bu metodlar bize SDP dönecek ve bizim bu dönen SDP’yi lokal SDP olarak atamamız ve sonrasında karşıya göndermemiz gerekli. Karşıdan gelen SDP’yi de karşı(remote) SDP olarak atayacağız. Böylelikle kuracağımız bağlantının bilgilerini ilgili eşlerle paylaşmış olacağız.</p><p><em>SDP(Session Description Protocol), duyuru ve davet amacıyla multimedya iletişim oturumlarını tanımlayan bir formattır. İçerisinde medya türleri ve codec bileşenleri gibi parametreleri barındırır.</em></p><pre>func offer(completion: @escaping (_ sdp: SessionDescription) -&gt; Void) {<br>    let constrains = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)<br>    peerConnection?.offer(for: constrains, completionHandler: { sdp, error in<br>        guard let sdp else { return }<br>        self.peerConnection?.setLocalDescription(sdp, completionHandler: { error in<br>            guard error == nil else { return }<br>            let sessionDescription = SessionDescription(from: sdp)<br>            completion(sessionDescription)<br>        })<br>    })<br>}<br><br>func answer(completion: @escaping(_ sdp: SessionDescription) -&gt; Void) {<br>    let constrains = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)<br>    peerConnection?.answer(for: constrains, completionHandler: { sdp, error in<br>        guard let sdp else { return }<br>        self.peerConnection?.setLocalDescription(sdp, completionHandler: { error in<br>            guard error == nil else { return }<br>            let sessionDescription = SessionDescription(from: sdp)<br>            completion(sessionDescription)<br>        })<br>    })<br>}<br><br>func setRemoteSDP(with sessionDescription: SessionDescription, completion: @escaping (Error?) -&gt; ()) {<br>    let rtcSessionDescription = sessionDescription.getRTCSessionDescription()<br>    peerConnection?.setRemoteDescription(rtcSessionDescription, completionHandler: completion)<br>}</pre><p>Bu aşamada SessionDescription objesi de oluşturdum.</p><pre>struct SessionDescription: Codable {<br>    enum CodingKeys: String, CodingKey {<br>        case type, sdp<br>    }<br>    <br>    var type: RTCSdpType<br>    var sdp: String<br>    <br>    init(type: RTCSdpType, sdp: String) {<br>        self.type = type<br>        self.sdp = sdp<br>    }<br>    <br>    init(from rtcSDP: RTCSessionDescription) {<br>        self.type = rtcSDP.type<br>        self.sdp = rtcSDP.sdp<br>    }<br>    <br>    init(from decoder: Decoder) throws {<br>        let values = try decoder.container(keyedBy: CodingKeys.self)<br>        let sdp = try values.decode(String.self, forKey: .sdp)<br>        let type = try values.decode(Int.self, forKey: .type)<br>        <br>        self.sdp = sdp<br>        self.type = RTCSdpType(rawValue: type) ?? .rollback<br>    }<br>    <br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(type.rawValue, forKey: .type)<br>        try container.encode(sdp, forKey: .sdp)<br>    }<br><br>    func getRTCSessionDescription() -&gt; RTCSessionDescription {<br>        RTCSessionDescription(type: type, sdp: sdp)<br>    }<br>}</pre><p>WebRTCClient’ı tamamlamak için son olarak ICE adaylarını ekleyeceğimiz fonksiyonu yazalım.</p><p><em>ICE(Internet Connectivity Establishment), eşten eşe (p2p) bağlantı da eşlerin mümkün olduğunca doğrudan konuşabilecekleri yolları bulmaya yarayan tekniktir. ICE adayı ise RTCPeerConnection oluşturmak için ICE tekniğini kullanacak eşi temsil eder.</em></p><pre>func setRemoteCandidate(with remoteCandidate: IceCandidate, completion: @escaping (Error?) -&gt; ()) {<br>    let candidate = remoteCandidate.getRTCIceCandidate()<br>    self.peerConnection?.add(candidate, completionHandler: completion)<br>}</pre><pre>struct IceCandidate: Codable {<br>    var sdpMid: String?<br>    var sdpMLineIndex: Int32<br>    var sdp: String<br>    <br>    init(from iceCandidate: RTCIceCandidate) {<br>        self.sdpMid = iceCandidate.sdpMid<br>        self.sdpMLineIndex = iceCandidate.sdpMLineIndex<br>        self.sdp = iceCandidate.sdp<br>    }<br>    <br>    func getRTCIceCandidate() -&gt; RTCIceCandidate {<br>        RTCIceCandidate(sdp: sdp, sdpMLineIndex: sdpMLineIndex, sdpMid: sdpMid)<br>    }<br>}</pre><p>Son olarak RTCPeerConnection tarafından oluşturulacak ICE adaylarını karşı tarafa iletmek için WebRTCClient’tan delege ile taşıyalım.</p><pre>protocol WebRTCClientDelegate: AnyObject {<br>    func peerConnection(didGenerate candidate: IceCandidate)<br>}</pre><pre>weak var delegate: WebRTCClientDelegate?</pre><pre>func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {<br>    debugPrint(&quot;peerConnection didGenerate candidate: \(candidate)&quot;)<br>    let iceCandidate = IceCandidate(from: candidate)<br>    delegate?.peerConnection(didGenerate: iceCandidate)<br>}</pre><p>Böylelikle WebRTCClient tarafında işimiz bitti. Son olarak ViewController tarafında kullanmak için WebRTCClientProtocolu de oluşturalım.</p><pre>protocol WebRTCClientProtocol {<br>    var delegate: WebRTCClientDelegate? { get set }<br>    func offer(completion: @escaping (_ sdp: SessionDescription) -&gt; Void)<br>    func answer(completion: @escaping(_ sdp: SessionDescription) -&gt; Void)<br>    func setRemoteSDP(with sessionDescription: SessionDescription, completion: @escaping (Error?) -&gt; ())<br>    func setRemoteCandidate(with remoteCandidate: IceCandidate, completion: @escaping (Error?) -&gt; ())<br>}</pre><p>Şimdi ViewController tarafına geçip WebRTCClient’ı entegre edelim.</p><pre>var webRTCClient: WebRTCClientProtocol?</pre><pre>func configureWebRTCClient() {<br>    webRTCClient = WebRTCClient()<br>    webRTCClient?.delegate = self<br>}</pre><pre>@IBAction func sendOffer(_ sender: Any) {<br>    debugPrint(&quot;sendOffer&quot;)<br>    webRTCClient?.offer(completion: { sdp in<br>        //TODO: implement<br>    })<br>}<br><br>@IBAction func sendAnswer(_ sender: Any) {<br>    debugPrint(&quot;sendAnswer&quot;)<br>    webRTCClient?.answer(completion: { sdp in<br>        //TODO: implement<br>    })<br>}</pre><pre>extension ViewController: WebRTCClientDelegate {<br>    func peerConnection(didGenerate candidate: IceCandidate) {<br>        //TODO: implement<br>    }<br>}</pre><p>Yavaş yavaş sona yaklaşıyoruz :) SDPleri ve Candidateleri soketten gönderme ve yakalama işleri kaldı. Şimdi onları da halledelim hemen.</p><p>İlk olarak işimizi kolaylaştırması adına bir SocketMessage objesi yazalım.</p><pre>enum SocketMessage: Decodable {<br>    case sdp(SessionDescription)<br>    case candidate(IceCandidate)<br>    <br>    static func generateMessageData(from candidate: IceCandidate) -&gt; Data {<br>        try! JSONEncoder().encode(SocketMessage.candidate(candidate))<br>    }<br>    <br>    static func generateMessageData(from sdp: SessionDescription) -&gt; Data {<br>        try! JSONEncoder().encode(SocketMessage.sdp(sdp))<br>    }<br>    <br>    static func decodeSocketMessage(from data: Data) -&gt; Self {<br>        try! JSONDecoder().decode(SocketMessage.self, from: data)<br>    }<br>}</pre><p>SocketClient tarafında ufak bir düzenleme yapıp Data yerine SocketMessage paslayalım.</p><pre>func handleSocketMessage(with message: SocketMessage)</pre><pre>case .binary(let data):<br>    debugPrint(&quot;Received data: \(data.count)&quot;)<br>    let socketMessage = SocketMessage.decodeSocketMessage(from: data)<br>    delegate?.handleSocketMessage(with: socketMessage)</pre><p>Sonrasında soket mesajlarını göndermek için SocketClientProtocol’e basit bir fonksiyon ekleyelim.</p><pre>func send(data: Data) {<br>    socket?.write(data: data)<br>}</pre><p>ViewController’a geri dönüp hem değişikliği uygulayalım hem de diğer soket işlerini halledelim.<br>İlk olarak handleSocketMessage’ı entegre edelim. Gelen SDP ve Candidateleri ilgili yerlere atayalım.</p><pre>func handleSocketMessage(with message: SocketMessage) {<br>    switch message {<br>    case .sdp(let sdp):<br>        webRTCClient?.setRemoteSDP(with: sdp, completion: { err in<br>            guard err == nil else { return }<br>            DispatchQueue.main.async {<br>                self.remoteSDPLabel.text = &quot;Remote SDP : 🟢&quot;<br>            }<br>        })<br>    case .candidate(let candidate):<br>        webRTCClient?.setRemoteCandidate(with: candidate, completion: { err in<br>            guard err == nil else { return }<br>            debugPrint(&quot;Remote candidate added: \(candidate)&quot;)<br>        })<br>    }<br>}</pre><p>Sonrasında karşı tarafa soket ile göndermemiz gerekenleri yazalım.<br>İlk olarak SDP göndermeyle başlayalım.</p><pre>@IBAction func sendOffer(_ sender: Any) {<br>    debugPrint(&quot;sendOffer&quot;)<br>    webRTCClient?.offer(completion: { sdp in<br>        let data = SocketMessage.generateMessageData(from: sdp)<br>        self.socket?.send(data: data)<br>        DispatchQueue.main.async {<br>            self.localSDPLabel.text = &quot;Local SDP : 🟢&quot;<br>        }<br>        <br>        debugPrint(&quot;Offer sdp: \(sdp)&quot;)<br>    })<br>}<br><br>@IBAction func sendAnswer(_ sender: Any) {<br>    debugPrint(&quot;sendAnswer&quot;)<br>    webRTCClient?.answer(completion: { sdp in<br>        let data = SocketMessage.generateMessageData(from: sdp)<br>        self.socket?.send(data: data)<br>        DispatchQueue.main.async {<br>            self.localSDPLabel.text = &quot;Local SDP : 🟢&quot;<br>        }<br>    })<br>}</pre><p>Sonrasında Candidateleri gönderelim.</p><pre>func peerConnection(didGenerate candidate: IceCandidate) {<br>    let data = SocketMessage.generateMessageData(from: candidate)<br>    socket?.send(data: data)<br>}</pre><p>Evet bitirdik :) Artık deneyebiliriz.</p><p>İki farklı simülatörden uygulamayı açalım. Birinden istek diğerinden cevap gönderelim. Ta daa! Sesimiz yankılanıyor :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*KZ5nYxJJjQwY0JpjwtiFWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*FsHZxed8X2HULb97a7gFqw.png" /></figure><p>Başarılı bir şekilde basit sesli sohbet uygulamamızı geliştirdik. Ancak şunu bilmenizi isterim ki sizleri sıkmamak ve anlatımı basit tutmak adına olabildiğince sadeleştirmeye çalıştım. Dolayısıyla bu yazı da anlatılmayan çok daha fazla konu var. Bunları işin içine girdikçe öğrenmenizde ve terimlerde boğulmamanızda fayda var.<br>GitHub reposuna <a href="https://github.com/yavuzaytekin/WebRTC-iOSSample">şuradan</a> ulaşabilirsiniz.</p><p><em>Not olarak burada localhostta çalıştık. Dolayısıyla gerçek dünya senaryolarından uzak bir çalışma oldu. Burada yazılan kodları kendi projenize eklemek isterseniz lütfen bu durumu göz önünde bulundurun.</em></p><p>Umarım faydalı ve açıklayıcı bir yazı olmuştur. Başka yazılarda görüşmek üzere hoşçakalın 👋👋</p><p>Yararlandığım Kaynaklar:<br><a href="https://en.wikipedia.org/wiki/WebRTC">https://en.wikipedia.org/wiki/WebRTC</a><br><a href="https://web.dev/webrtc-basics/">https://web.dev/webrtc-basics/</a><br><a href="https://webrtc.org/">https://webrtc.org/</a><br><a href="https://en.wikipedia.org/wiki/Session_Description_Protocol">https://en.wikipedia.org/wiki/Session_Description_Protocol</a><br><a href="https://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment">https://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment</a><br><a href="https://github.com/stasel/WebRTC-iOS">https://github.com/stasel/WebRTC-iOS</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a445328de2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/webrtc-ile-basit-sesli-sohbet-uygulamas%C4%B1-4a445328de2">WebRTC ile Basit Sesli Sohbet Uygulaması</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is CloudKit?]]></title>
            <link>https://medium.com/ios-nest/what-is-cloudkit-429747ddcf2f?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/429747ddcf2f</guid>
            <category><![CDATA[cloudkit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 14:09:27 GMT</pubDate>
            <atom:updated>2025-12-17T14:09:25.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9J2g-ZZipIxpponpQWSvhQ.png" /></figure><p>CloudKit is <strong>Apple’s cloud database service for app developers</strong>, built on top of iCloud and tightly integrated with Apple ID.</p><p>At a high level, CloudKit lets your app:</p><ul><li><strong>Store data in the cloud</strong></li><li><strong>Sync that data across a user’s devices</strong></li><li><strong>Share data between users</strong></li><li><strong>Work offline and sync later</strong></li></ul><p>Because it’s built on iCloud, you don’t manage servers, user accounts, or tokens. Your app talks directly to Apple’s infrastructure through the CloudKit framework, and the user signs in with their existing Apple ID.</p><p>This makes CloudKit especially appealing when your target audience is <strong>purely Apple users</strong> and you want a reliable, offline-friendly sync layer without running your own backend.</p><h3>Core Concepts: The Mental Model</h3><p>To understand CloudKit, it helps to map its concepts to things you already know:</p><ul><li><strong>Container</strong></li></ul><p>Think of a container as your app’s <strong>namespace in iCloud</strong>. It’s the sandbox that holds your app’s data and configuration. An app usually has one primary container (e.g. iCloud.com.yourcompany.yourapp).</p><ul><li><strong>Databases</strong></li></ul><p>Each container exposes three logical databases:</p><ul><li><strong>Private Database</strong> — Data that belongs to a specific user. Only that user (and your app) can access it.</li><li><strong>Public Database</strong> — Data visible to all users of your app.</li><li><strong>Shared Database</strong> — Data that one user shares with others (e.g. shared notes, albums).</li><li><strong>RecordType</strong></li></ul><p>Similar to a table schema. A Note, Task, or Post would each be a RecordType with defined fields.</p><ul><li><strong>Record</strong></li></ul><p>A single instance of a RecordType — essentially a row/object. For example, one note inside the Note RecordType.</p><ul><li><strong>Zone</strong></li></ul><p>A logical grouping of records, mainly used for <strong>sync and conflict resolution</strong>. You can keep related data in the same zone to manage conflicts more intelligently.</p><ul><li><strong>Asset</strong></li></ul><p>Used for <strong>large binary data</strong> such as images, documents, or other files. Assets are stored in iCloud and referenced from your records.</p><p>If you’re coming from a relational database mindset, you can roughly map it like this:</p><blockquote><em>Container → Database → RecordType → Record</em></blockquote><blockquote><em>(with Zones and Assets as extra building blocks for sync and files)</em></blockquote><h3>Where CloudKit Fits Best: Common Use Cases</h3><p>CloudKit is not a one-size-fits-all backend, but in the right scenarios it’s extremely powerful.</p><h3>1. Personal User Data (Private Database)</h3><p>Great for anything that belongs strictly to one user:</p><ul><li>Health tracking data</li><li>Personal notes and to-do lists</li><li>App settings, preferences, and layouts</li><li>Private photo or document storage</li></ul><p>Here, everything lives in the <strong>Private Database</strong>, which is automatically scoped to the user’s Apple ID. Other users can’t see this data.</p><h3>2. Public Community Data (Public Database)</h3><p>Use the <strong>Public Database</strong> when your content is meant to be visible to everyone:</p><ul><li>Public forums or message boards</li><li>Game leaderboards</li><li>Shared knowledge bases (e.g. public guides, recipes)</li><li>Event announcements or public listings</li></ul><p>All users can read from the Public Database; writes are typically controlled by your app’s logic.</p><h3>3. Shared Data Between Users (Shared Database)</h3><p>The <strong>Shared Database</strong> sits in between purely personal and fully public data. It’s all about <em>sharing specific items</em> with specific people:</p><ul><li>Shared photo albums</li><li>Collaborative documents or notes</li><li>Shared calendars</li><li>Team task lists</li></ul><p>CloudKit can generate unique share links and lets you configure permission levels: read-only or read-write. Under the hood, it uses CloudKit Sharing, and those shared records appear in the Shared Database for participants.</p><h3>4. Offline-First Mobile Experiences</h3><p>One of CloudKit’s biggest strengths is <strong>offline-first behavior</strong>:</p><ul><li>The app can create or edit records <strong>while offline</strong>.</li><li>Data is cached locally.</li><li>When the network is back, CloudKit <strong>syncs changes automatically</strong>.</li></ul><p>This naturally leads to the problem of <strong>conflicts</strong>: what happens if a user edits the same record on multiple devices while offline?</p><p>By default, CloudKit uses a simple <strong>“last writer wins”</strong> strategy. But you can implement custom conflict resolution by inspecting record metadata (like change tokens) and:</p><ul><li>Showing both versions to the user, or</li><li>Merging fields intelligently, depending on your use case.</li></ul><h3>5. Notifications &amp; Subscriptions</h3><p>CloudKit has a powerful concept called <strong>subscriptions</strong>, which lets your app be notified when data changes on the server.</p><p>You can:</p><ul><li>Subscribe to changes for a specific <strong>RecordType</strong> or <strong>query</strong></li><li>Receive <strong>push notifications</strong> when records are created, updated, or deleted</li><li>Build live features like:</li><li>Activity feeds</li><li>Real-time collaboration</li><li>Chat-like experiences</li></ul><p>Importantly, CloudKit handles the infrastructure for you: no polling loops, no custom notification server. Apple’s servers track changes and send push notifications (including silent pushes) via APNs, allowing your app to sync in the background.</p><h3>6. Hybrid Architectures</h3><p>CloudKit doesn’t have to be the only backend in your stack.</p><p>Common hybrid patterns:</p><ul><li><strong>Core Data + CloudKit</strong></li></ul><p>Use Core Data as your local database and CloudKit as the sync layer. This gives you fast local reads with robust cloud sync.</p><ul><li><strong>CloudKit + Other Backends (e.g. Firebase)</strong></li></ul><p>For example, use CloudKit for user-specific iOS data and another backend for platform-agnostic services (web/Android).</p><p>This hybrid approach is useful when you want the UX benefits of CloudKit but still need cross-platform support or custom server logic elsewhere.</p><h3>Architecture: How CloudKit Works Under the Hood</h3><p>At a high level, the architecture is:</p><blockquote><em>App ↔︎ CloudKit Framework ↔︎ iCloud Servers</em></blockquote><p>A few key pieces:</p><ul><li><strong>Apple ID–based Authentication</strong></li></ul><p>If the user is signed into iCloud on their device, they’re effectively authenticated for CloudKit. You don’t build a custom login screen for them. There are APIs to check account status and availability, but no OAuth dance or password handling.</p><ul><li><strong>CRUD via CloudKit APIs</strong></li></ul><p>You work with:</p><p>CKContainer to access your container</p><p>CKDatabase for the Private, Public, and Shared databases</p><p>CKRecord and CKRecord.ID to represent data</p><p>CKQuery to fetch records</p><p>Operations like CKModifyRecordsOperation for batch changes</p><ul><li><strong>Offline-First with Local Caching</strong></li></ul><p>CloudKit keeps certain metadata and change tokens locally, and operations can be retried when the network becomes available — but your app is still responsible for managing its own local storage strategy.</p><ul><li><strong>Conflict Resolution</strong></li></ul><p>The default is “last writer wins,” but you can implement custom resolution by analyzing record change info and deciding which fields to keep or merge.</p><p>The net effect: <strong>you focus on the data model, not on running servers or designing a sync protocol.</strong></p><h3>CloudKit Dashboard: Your Control Panel</h3><p>Apple provides a web-based <strong>CloudKit Dashboard</strong> in the Apple Developer Portal, which acts as your admin console.</p><p>From the dashboard you can:</p><ul><li>Manage <strong>containers</strong> and their databases</li><li>Define and edit <strong>RecordType schemas</strong> (e.g. Note with title, content, createdAt)</li><li>Inspect, edit, or delete stored records for debugging</li><li>Switch between <strong>development</strong> and <strong>production</strong> environments</li></ul><p>The separation between development and production is important: you can freely experiment and break things in the development container without affecting real users in production.</p><p>In practice, the dashboard replaces a lot of what you might normally need a custom admin UI or backend console for.</p><h3>Working with CloudKit in Code</h3><p>On the code side, you’ll mostly interact with a small set of types:</p><ul><li><strong>CKContainer</strong> — Entry point to your CloudKit environment.</li></ul><pre>let container = CKContainer.default()</pre><ul><li><strong>CKDatabase</strong> — Represents a specific database:</li></ul><pre>let privateDB = container.privateCloudDatabase<br>let publicDB  = container.publicCloudDatabase</pre><ul><li><strong>CKRecord &amp; CKRecord.ID</strong> — Your data objects.</li></ul><pre>let record = CKRecord(recordType: &quot;Note&quot;)<br>record[&quot;title&quot;] = &quot;Meeting Notes&quot;</pre><ul><li><strong>CKQuery</strong> — To fetch records with predicates.</li><li><strong>CKModifyRecordsOperation</strong> — To save/delete multiple records in one batch.</li><li><strong>CKSubscription</strong> — To set up server-side subscriptions for change notifications.</li></ul><p>You don’t need to memorize every class to get started. Conceptually, think of it as:</p><blockquote><em>“Create records → save to database → query them back → optionally subscribe to changes.”</em></blockquote><h3>Advantages of CloudKit</h3><p>Why would you pick CloudKit over rolling your own backend or using a generic BaaS?</p><ul><li><strong>Deep Integration with Apple Platforms</strong></li><li>Works seamlessly across iOS, macOS, watchOS, and tvOS. Authentication via Apple ID feels native and familiar to users.</li><li><strong>No Backend Maintenance</strong></li><li>No servers to deploy, no scaling, no patching, no database cluster to babysit. Apple runs the infrastructure.</li><li><strong>Generous Free Tier</strong></li><li>Each Apple ID and app gets free storage and request quotas that are enough for many small and medium-sized apps.</li><li><strong>Offline-First by Design</strong></li><li>Local caching and automatic sync are built in, which is a big win for mobile UX.</li><li><strong>Built-in Push Notifications for Data Changes</strong></li><li>Subscriptions let you react to server-side changes without custom polling logic or a notification backend.</li></ul><h3>Limitations and Trade-Offs</h3><p>CloudKit isn’t magic, and it’s not for every project. Some important limitations:</p><ul><li><strong>Apple-Only</strong></li><li>CloudKit is tightly coupled to Apple’s ecosystem. If you need a <strong>first-class Android or web client</strong>, CloudKit alone won’t be enough.</li><li><strong>Limited Query Capabilities</strong></li></ul><p>CKQuery predicates are useful, but you don’t get the full power of a relational database:</p><ul><li>No joins</li><li>Limited aggregations</li><li>Less flexibility for complex analytics</li><li>This means you need to design your data model carefully up front.</li><li><strong>Schema Planning Matters</strong></li><li>RecordType schemas are defined in the dashboard and must be handled carefully in production. Poor early decisions can make later migrations painful.</li><li><strong>Costs Beyond the Free Tier</strong></li><li>Once you exceed the free quotas (especially with heavy usage of the Public Database), you’ll incur costs. For large-scale apps, you still need to do capacity and cost planning.</li></ul><p>In short: <strong>CloudKit is fantastic when your use case fits, but it’s not a universal backend substitute.</strong></p><h3>When Should You Use CloudKit?</h3><p>CloudKit makes a lot of sense when:</p><ul><li>Your target users are <strong>primarily on Apple devices</strong></li><li>You want <strong>sync and offline support</strong> without building a backend</li><li>Your data model is relatively straightforward (records, simple relationships)</li><li>You value <strong>native integration</strong> and minimal friction around authentication</li></ul><p>It’s less ideal when:</p><ul><li>You need full cross-platform support (Android, web)</li><li>You require advanced querying or analytics</li><li>You want full control over server-side logic and infrastructure</li></ul><p>If you’re building an Apple-only app and you find yourself procrastinating on designing a full backend, it’s worth asking:</p><blockquote><em>“Can this be a CloudKit problem instead of a server problem?”</em></blockquote><p>In many cases, the answer will be yes — and that can save you a lot of time, complexity, and maintenance in the long run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=429747ddcf2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/what-is-cloudkit-429747ddcf2f">What is CloudKit?</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing User Experience in iOS Development]]></title>
            <link>https://medium.com/ios-nest/enhancing-user-experience-in-ios-development-a0df1897cb3c?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/a0df1897cb3c</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 14:09:12 GMT</pubDate>
            <atom:updated>2025-12-17T14:09:11.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OtIexMkE7lyBGTRwRtKk3g.jpeg" /></figure><p>In today’s digital landscape, user experience (UX) is a cornerstone of successful product design. This article delves into how <strong>Human Interface Guidelines (HIG)</strong> and psychological principles can be applied to iOS app design, fostering a user-centered experience.</p><h4><strong>Human Interface Guidelines (HIG)</strong></h4><p>Apple’s <strong>Human Interface Guidelines (HIG)</strong> serve as a blueprint for creating intuitive and seamless user experiences. Key takeaways from HIG include:</p><ul><li><strong>Focus on Primary Tasks</strong></li></ul><p>Minimize on-screen controls to help users stay focused on the main task. Secondary actions should be easy to locate with minimal effort.</p><ul><li><strong>Seamless Adaptation</strong></li></ul><p>Ensure the app adapts automatically to changes like orientation, Dark Mode, and text size, enabling users to set their preferences effortlessly.</p><ul><li><strong>Comfortable Interactions</strong></li></ul><p>Place controls within easy reach, focusing on the lower or middle areas of the screen. Support intuitive gestures like swipe-to-go-back for enhanced usability.</p><ul><li><strong>Enhanced Functionality with Permissions</strong></li></ul><p>With user consent, leverage platform features such as biometrics, payments, and location to enrich app functionality without adding complexity.</p><h4><strong>The Role of Psychological Principles in UX Design</strong></h4><p>Applying psychological principles ensures a user-friendly interface. Here’s how popular UX laws can be leveraged:</p><ul><li><strong>Law of Proximity</strong></li></ul><p>Group related elements together while maintaining adequate spacing for readability and usability. Overcrowding reduces clarity and increases the likelihood of user errors.</p><ul><li><strong>Hick’s Law</strong></li></ul><p>Simplify decision-making by limiting choices. The fewer options available, the faster users can make decisions.</p><ul><li><strong>Fitts’s Law</strong></li></ul><p>The time required to interact with a target depends on its size and distance. Ensure buttons and interactive areas are large enough and positioned for easy access.</p><ul><li><strong>Jakob’s Law</strong></li></ul><p>Users prefer familiar experiences. Design your app in line with conventions and patterns they already know to reduce cognitive load.</p><ul><li><strong>Tesler’s Law</strong></li></ul><p>While inherent complexity cannot always be eliminated, strive to simplify the user experience wherever possible. Clear terminology and straightforward workflows are key.</p><ul><li><strong>Law of Pragnanz</strong></li></ul><p>People naturally interpret complex visuals in the simplest way possible. Opt for clean, minimal designs that emphasize clarity.</p><ul><li><strong>Miller’s Law</strong></li></ul><p>Short-term memory can only hold 7±2 items. Limit navigation options and group information into smaller, manageable chunks.</p><h4><strong>Putting It All Together</strong></h4><p>By combining HIG standards with psychological principles, you can create applications that are not only visually appealing but also intuitive and efficient. For example:</p><ul><li>Use an <strong>8-point grid system</strong> for consistent spacing and alignment.</li><li>Keep navigation menus concise, ideally with 5–7 options.</li><li>Prioritize user familiarity by incorporating universally recognized icons (e.g., stars or hearts for favoriting).</li></ul><p><strong>Conclusion</strong></p><p>iOS app design is both an art and a science. By following <strong>Human Interface Guidelines (HIG)</strong> and applying psychological principles, designers can craft user-centered, accessible, and enjoyable experiences. These strategies not only improve usability but also ensure long-term user satisfaction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0df1897cb3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/enhancing-user-experience-in-ios-development-a0df1897cb3c">Enhancing User Experience in iOS Development</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Memory Leaks Using Unit Tests]]></title>
            <link>https://medium.com/ios-nest/detecting-memory-leaks-using-unit-tests-e4dda705ec0f?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4dda705ec0f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Mert]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 14:08:53 GMT</pubDate>
            <atom:updated>2025-12-17T14:08:44.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kQOcAFXdqEe55qeZqql0A.png" /></figure><p>In the fast-paced world of app development, user experience is paramount. Yet, one silent culprit can degrade performance, cause crashes, and frustrate users — <strong>memory leaks</strong>. These elusive bugs sneak into our apps when objects remain in memory longer than needed, often due to retain cycles or improper cleanup. For iOS developers, detecting memory leaks is crucial to maintaining smooth and efficient applications.</p><p>This article explores how to <strong>detect memory leaks using unit tests</strong> in Swift, providing a robust framework to catch leaks before they wreak havoc on your app’s performance.</p><h4><strong>What are Memory Leaks and Why Do They Matter?</strong></h4><p>A <strong>memory leak</strong> occurs when an object that is no longer needed remains in memory because it is still strongly referenced. This can lead to:</p><ul><li><strong>Decreased performance:</strong> Unnecessary objects consume memory and slow down the app.</li><li><strong>Crashes:</strong> Over time, the app may consume too much memory, leading to system-imposed termination.</li><li><strong>Poor user experience:</strong> Lagging and freezing degrade usability.</li></ul><p><strong>Common Causes of Memory Leaks in Swift</strong></p><ul><li><strong>Retain Cycles:</strong> Two or more objects hold strong references to each other, preventing deallocation.</li><li><strong>Unreleased Observers:</strong> Objects registered as observers in NotificationCenter but not removed.</li><li><strong>Timers:</strong> Timer instances retain their target object unless invalidated.</li></ul><p><strong>Setting Up Unit Tests for Memory Leak Detection in Swift</strong></p><p>Unit tests provide a systematic approach to detecting memory leaks. By leveraging <strong>weak references</strong>, you can verify whether objects are properly deallocated after they are no longer needed. This technique ensures that your application is free from unnecessary memory consumption, which can lead to performance degradation or crashes.</p><p>Here’s how to set up unit tests for memory leak detection in Swift, with an example focusing on <strong>closures</strong>.</p><p><strong>What Causes Memory Leaks in Closures?</strong></p><p>A closure retains any variables or objects referenced within its body. If the closure references self without breaking the strong reference (using [weak self] or [unowned self]), it can create a retain cycle:</p><p>1. <strong>Object A</strong> retains <strong>Closure B</strong>.</p><p>2. <strong>Closure B</strong> retains <strong>Object A</strong> via self.</p><p>This circular reference prevents ARC from deallocating either object, resulting in a memory leak.</p><p><strong>Step-by-Step: Detecting Retain Cycles in Closures</strong></p><p><strong>Example: Retain Cycle in a Closure</strong></p><p>Here’s a class that uses a closure without managing the strong reference to self:</p><pre>class ClosureRetainCycle {<br>    var name: String<br>    var closure: (() -&gt; Void)?<br><br>    init(name: String) {<br>        self.name = name<br>    }<br><br>    func createRetainCycle() {<br>        closure = {<br>            print(self.name)<br>        }<br>    }<br><br>    deinit {<br>        print(&quot;ClosureRetainCycle instance deinitialized.&quot;)<br>    }<br>}</pre><p><strong>Testing for Memory Leaks</strong></p><p>To verify that no memory leaks exist, we can write a unit test using weak references. The goal is to confirm that the object is deallocated when it goes out of scope.</p><p><strong>Unit Test:</strong></p><pre>import XCTest<br>@testable import MemoryLeakDetection<br><br>class ClosureRetainCycleTests: XCTestCase {<br><br>    func testClosureRetainCycle() {<br>        // Arrange<br>        var instance: ClosureRetainCycle? = ClosureRetainCycle(name: &quot;Test Name&quot;)<br>        weak var weakInstance = instance<br><br>        // Act<br>        instance?.createRetainCycle()<br>        instance = nil // Break the strong reference<br><br>        // Assert<br>        XCTAssertNil(weakInstance, &quot;ClosureRetainCycle instance should have been deallocated. Retain cycle detected!&quot;)<br>    }<br>}</pre><p><strong>How the Test Works</strong></p><p>1. <strong>Weak Reference:</strong></p><p>• A weak reference (weakInstance) is created to track the lifecycle of ClosureRetainCycle.</p><p>2. <strong>Deallocation Check:</strong></p><p>• After setting instance = nil, weakInstance should also become nil. If not, it means a retain cycle is preventing deallocation.</p><p>3. <strong>Test Assertion:</strong></p><ul><li>If weakInstance is not nil, the test fails, signaling a memory leak.</li></ul><p><strong>Fixing the Retain Cycle</strong></p><p>To fix this issue, use [weak self] within the closure to break the strong reference to self:</p><p><strong>Updated Implementation:</strong></p><pre>func createRetainCycle() {<br>    closure = { [weak self] in<br>        guard let self else { return }<br>        print(self.name)<br>    }<br>}</pre><p><strong>Key Takeaways</strong></p><p>1. <strong>Always Test Closures:</strong> Closures are powerful but prone to creating retain cycles if not managed properly.</p><p>2. <strong>Write Unit Tests:</strong> Leverage weak references to confirm objects are deallocated.</p><p>3. <strong>Use Debugging Tools:</strong> Combine tests with tools like the Memory Graph Debugger to catch leaks early.</p><p>By systematically testing closures and other potential sources of memory leaks, you can ensure your Swift application remains performant and efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4dda705ec0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/detecting-memory-leaks-using-unit-tests-e4dda705ec0f">Detecting Memory Leaks Using Unit Tests</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Design Pattern in iOS]]></title>
            <link>https://medium.com/ios-nest/factory-design-pattern-in-ios-fcc84a9047ff?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/fcc84a9047ff</guid>
            <category><![CDATA[design-patterns-in-ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ezgi Üstünel]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 09:50:29 GMT</pubDate>
            <atom:updated>2025-12-17T09:50:14.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKNJQaH3DSp30oWFvPj9yw.png" /></figure><p>Hello. This article will examine the Factory Design Pattern in Swift programming language and try to make it understandable with various code snippets. Let’s get started.</p><h4>What is Factory Design Pattern?</h4><p>It is also known as a creational pattern. It can be defined as a structure that allows us to create objects without knowing what class type they are. Let’s detail this definition with a more entertaining example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOJ1H_dMGk5DzcHvYDo8VA.png" /></figure><p>Let’s say we have a toy factory. The factory in the Factory Design Pattern does exactly what this toy factory does. In other words, when a customer comes and says I want a toy house, we don’t say, excuse me, we can only produce toy cars. We have the infrastructure to produce toy houses, cars, and airplanes. We don’t need to make any uber-changes in our infrastructure or make extra efforts for this. Through this structure, we can produce any toy, regardless of the type of toy. This is how we can define the basic logic of the Factory Design Pattern.</p><h4>When should you use it?</h4><p>It can be used if multiple related classes use the same protocol or when you want to create the screens not directly but with the help of a factory.</p><p>The factory design pattern can also be used when there is a single screen in the project. Let’s say the customer has applied somewhere. Your system is only responsible for sending an email saying whether your application was accepted or not or waiting for a process. In other words, it can be used easily in a system that has only one job. It only depends on the project&#39;s needs.</p><h4>Example 1</h4><p>Let’s say we have 3 shape classes square, circle, and rectangle. These classes are derived from ShapeHelper object.</p><pre>fileprivate class Square: ShapeHelper {<br>    override func configure() {<br>        let frame = CGRect(x: 0, y: 0, width: height, height: height)<br>        view.frame = frame<br>        view.backgroundColor = defaultColor<br>    }<br>}<br><br>fileprivate class Circle: ShapeHelper {<br>    override func configure() {<br>        super.configure()<br>        view.layer.cornerRadius = view.frame.width / 2<br>        view.layer.masksToBounds = true<br>    }<br>}<br><br>fileprivate class Rectangle: ShapeHelper {<br>    override func configure() {<br>        let frame = CGRect(x: 0, y: 0, width: height + height/2, height: height)<br>        view.frame = frame<br>        view.backgroundColor = UIColor.blue<br>    }<br>}</pre><p>ShapeHelper class conforms HelperViewFactoryProtocol. We can think of this protocol as having definitions of methods that can be used in all shape types.</p><pre>fileprivate class ShapeHelper: HelperViewFactoryProtocol {<br>    let height: Int<br>    let parentView: UIView<br>    var view: UIView<br><br>    init(height: Int = defaultHeight, parentView: UIView) {<br>        self.height = height<br>        self.parentView = parentView<br>        view = UIView()<br>    }<br><br>    func configure() {<br>        let frame = CGRect(x: 0, y: 0, width: height, height: height)<br>        view.frame = frame<br>        view.backgroundColor = defaultColor<br>    }<br><br>    func position() {<br>        view.center = parentView.center<br>    }<br><br>    func display() {<br>        configure()<br>        position()<br>        parentView.addSubview(view)<br>    }<br>}</pre><pre>protocol HelperViewFactoryProtocol {<br>    func configure()<br>    func position()<br>    func display()<br>    var height: Int { get }<br>    var view: UIView { get }<br>    var parentView: UIView { get }<br>}</pre><p>Let’s create a factory class called ShapeFactory that will allow us to create these classes. This class has a method called “<strong>create”</strong>. This method creates the relevant class according to the shape parameter it takes.</p><pre>enum Shape {<br>    case square<br>    case circle<br>    case rectangle<br>}<br><br>class ShapeFactory {<br>    let parentView: UIView<br><br>    init(parentView: UIView) {<br>        self.parentView = parentView<br>    }<br><br>    func create(as shape: Shape) -&gt; HelperViewFactoryProtocol {<br>        switch shape {<br>        case .square:<br>            let square = Square(parentView: parentView)<br>            return square<br>        case .circle:<br>            let circle = Circle(parentView: parentView)<br>            return circle<br>        case .rectangle:<br>            let rectangle = Rectangle(parentView: parentView)<br>            return rectangle<br>        }<br>    }<br>}</pre><p>Now, let’s look at how to use it:</p><pre>    func drawCircle(_ sender: Any) {<br>        createShape(.circle, on: view)<br>    }<br><br>    func drawSquare(_ sender: Any) {<br>        createShape(.square, on: view)<br>    }<br><br>    func drawRectangle(_ sender: Any) {<br>        createShape(.rectangle, on: view)<br>    }<br><br>    private func createShape(_ shape: Shape, on view: UIView) {<br>        let shapeFactory = ShapeFactory(parentView: view)<br>        shapeFactory.create(as: shape).display()<br>    }</pre><h4>Example 2</h4><p>In this example, let’s assume that there are 3 different article types in the project. TextArticle, VideoArticle, and AudioArticle. These classes conform ArticleProtocol, which contains the common methods and parameters of all articles.</p><pre>protocol ArticleProtocol {<br>    var title: String { get }<br>    var author: String { get }<br>    var date: Date { get }<br>    var image: UIImage? { get }<br>    var content: String { get }<br>    var type: ArticleType { get }<br>}<br><br>enum ArticleType {<br>    case text<br>    case video<br>    case audio<br>}<br><br>class TextArticle: ArticleProtocol {<br>    var title: String<br>    var author: String<br>    var date: Date<br>    var image: UIImage?<br>    var content: String<br>    var type: ArticleType = .text<br><br>    init(title: String, author: String, date: Date, image: UIImage?, content: String) {<br>        self.title = title<br>        self.author = author<br>        self.date = date<br>        self.image = image<br>        self.content = content<br>    }<br>}<br><br>class VideoArticle: ArticleProtocol {<br>    var title: String<br>    var author: String<br>    var date: Date<br>    var image: UIImage?<br>    var content: String<br>    var type: ArticleType = .video<br>    var videoURL: URL<br><br>    init(title: String, author: String, date: Date, image: UIImage?, content: String, videoURL: URL) {<br>        self.title = title<br>        self.author = author<br>        self.date = date<br>        self.image = image<br>        self.content = content<br>        self.videoURL = videoURL<br>    }<br>}<br><br>class AudioArticle: ArticleProtocol {<br>    var title: String<br>    var author: String<br>    var date: Date<br>    var image: UIImage?<br>    var content: String<br>    var type: ArticleType = .audio<br>    var audioURL: URL<br><br>    init(title: String, author: String, date: Date, image: UIImage?, content: String, audioURL: URL) {<br>        self.title = title<br>        self.author = author<br>        self.date = date<br>        self.image = image<br>        self.content = content<br>        self.audioURL = audioURL<br>    }<br>}</pre><p>Instead of directly initiating these article classes, produce them according to the relevant type with the help of the ArticleFactory class.</p><pre>class ArticleFactory {<br>    func createArticle(data: [String: Any]) -&gt; ArticleProtocol? {<br>        guard let type = data[&quot;type&quot;] as? String else { return nil }<br>        let title = data[&quot;title&quot;] as? String ?? &quot;&quot;<br>        let author = data[&quot;author&quot;] as? String ?? &quot;&quot;<br>        let date = data[&quot;date&quot;] as? Date ?? Date()<br>        let image = data[&quot;image&quot;] as? UIImage ?? nil<br>        let content = data[&quot;content&quot;] as? String ?? &quot;&quot;<br><br>        switch type {<br>        case &quot;text&quot;:<br>            return TextArticle(title: title, author: author, date: date, image: image, content: content)<br>        case &quot;video&quot;:<br>            guard let videoURL = data[&quot;video_url&quot;] as? URL else { return nil }<br>            return VideoArticle(title: title, author: author, date: date, image: image, content: content, videoURL: videoURL)<br>        case &quot;audio&quot;:<br>            guard let audioURL = data[&quot;audio_url&quot;] as? URL else { return nil }<br>            return AudioArticle(title: title, author: author, date: date, image: image, content: content, audioURL: audioURL)<br>        default:<br>            return nil<br>        }<br>    }<br>}</pre><h4>Example 3</h4><p>Let’s say there is a factory that produces music genres(pop, rock, and rap) in this example. MusicGenreFactory protocol defines methods that will allow us to produce music genres. To establish a more flexible structure in large projects, it can be useful to proceed with protocol definitions.</p><p>In this example, let’s proceed by creating a factory class for each genre, thus establishing a more decoupled structure. Each factory class conforms MusicGenreFactory protocol and can use the “<em>createMusicGenre</em>” method to create the genre classes.</p><pre>protocol MusicGenreFactory {<br>    func createMusicGenre() -&gt; MusicGenre<br>}<br><br>class PopFactory: MusicGenreFactory {<br><br>    func createMusicGenre() -&gt; MusicGenre {<br>        return PopMusic()<br>    }<br>}<br><br>class RockFactory: MusicGenreFactory {<br><br>    func createMusicGenre() -&gt; MusicGenre {<br>        return RockMusic()<br>    }<br>}<br><br>class RapFactory: MusicGenreFactory {<br><br>    func createMusicGenre() -&gt; MusicGenre {<br>        return RapMusic()<br>    }<br>}</pre><p>In concrete class definitions, each class contains methods to do its special work. If there are common processes for each genre, it may be easier to collect these methods in a protocol.</p><pre>protocol MusicGenre {<br>    var composerList: [String] { get }<br><br>    func update(with composerList: [String])<br>}<br><br>class PopMusic: MusicGenre {<br>    var composerList: [String] = []<br>    <br>    func update(with composerList: [String]) {<br>        self.composerList = composerList<br>    }<br>}<br><br>class RapMusic: MusicGenre {<br>    var composerList: [String] = []<br><br>    func update(with composerList: [String]) {<br>        self.composerList = composerList<br>    }<br>}<br><br>class RockMusic: MusicGenre {<br>    var composerList: [String] = []<br><br>    func update(with composerList: [String]) {<br>        self.composerList = composerList<br>    }<br>}</pre><p>Here is an example of how to use the MusicGenreFactory class to create a music genre:</p><pre>class ViewController: UIViewController {<br>    private var currentGenre: MusicGenre?<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>    }<br><br>    func apply(with factory: MusicGenreFactory) {<br><br>        let genre = factory.createMusicGenre()<br>        genre.update(with: [&quot;&quot;])<br>    }<br>}</pre><h4>What are the advantages of this pattern?</h4><p>Flexibility: It makes your code more flexible because make updates without having to change your code.</p><p>Reusability: It makes the code more reusable because we can reuse the same factories to create different types of objects in different parts of the project.</p><p>Testability: It makes your code more testable because it allows you to mock factories in the unit tests.</p><p>Decoupling: It decouples your code from other object creation logic, which makes it easier to maintain and update your code.</p><h4>What are the disadvantages of this pattern?</h4><p>Complexity: If there are too many factory classes in the project, it can create complexity.</p><p>Performance Overhead: It can occur a small performance overhead due to the complexity it creates.</p><p>Tight coupling: We should be careful about creating tightly coupled classes that are dependent on each other because this makes it difficult to maintain and update the project.</p><h4>Finally</h4><p>If we are using software architecture in our projects, questions like how can factory design pattern be used in this architecture may come to mind. Both factory and all other design patterns can be very useful for solving the bottlenecks in the architecture we use. For example, factory design pattern can be very useful in separating view layer display models due to the same business logic but different response models.</p><p>This marks the end of this post so make sure to click on <strong>the clap button</strong>👏👏 if you liked it. See you in future posts…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc84a9047ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/factory-design-pattern-in-ios-fcc84a9047ff">Factory Design Pattern in iOS</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Screen Time API]]></title>
            <link>https://medium.com/ios-nest/screen-time-api-d1110751d2ce?source=rss----b2c468807414---4</link>
            <guid isPermaLink="false">https://medium.com/p/d1110751d2ce</guid>
            <category><![CDATA[screen-time-control]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ezgi Üstünel]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 09:41:15 GMT</pubDate>
            <atom:updated>2025-12-17T09:41:14.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BKPNT-mT6O--xxbG" /></figure><p>Hello, in this article I will share some information about Screen Time API and try to make it understandable with various code snippets. Let’s get started.</p><h4>What is Screen Time API?</h4><p>In the Apple document, it is stated in one sentence “Empower users to manage their device settings and usage while maintaining user privacy.” If we were to elaborate on this definition a little more, the Screen Time API helps us control the amount of time we spend in front of devices, both for ourselves and our children. This API has an environment where multiple frameworks work together. Let’s briefly examine these frameworks.</p><p><strong>Frameworks</strong></p><p><em>ScreenTime Framework</em> is used by parents to monitor their children’s web usage. This includes web usage reporting, deleting history, and applying child restrictions. However, it should be noted that this framework is not an entry point or umbrella framework, contrary to its name, meaning it does not encompass other frameworks. It is a framework tasked with a job on its own.</p><p><em>FamilyControls</em> allows parental control applications. We also need to import this framework to request screen time permission on your device. We can request this permission from the user thanks to a method in this framework that I will discuss shortly.</p><p><em>ManagedSettings &amp; ManagedSettingsUI</em> are used to restrict access to settings on the device, such as limiting media playback, restricting in-app purchases, or locking password settings.</p><p><em>DeviceActivity</em> is used to track user activity. What are these activities? Including applications, web usage, notifications received, and phone unlocking operations. DeviceActivity offers some methods and extensions to perform these actions. We will discuss them in the later stages of the article.</p><p><strong>Family Controls Entitlement</strong></p><p>First of all, in order to use all these frameworks that I just mentioned, Apple requires us to ask permission from the user. For this, you need to add family controls entitlement to Xcode settings. If you do not add it as capability, you cannot see the popup. In the images below, you can see how to add family controls capability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*yGebWJtLeSHFHjTz7bBGCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8Itbi5iKNcoA6Oa4SkdwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0qarDH4rQZcJCtW9Aj8Hg.png" /></figure><p><strong>Asking for Permissions</strong></p><p>After adding Capability, we can run the following code block on whichever screen of the app we want to display and request permission. Here, we have selected the request type as an individual, meaning we want this permission for our device, but if you have a family sharing account, you can also request this permission for your child. If you want to revoke the permission, you can run the code block below.</p><pre>Task {<br>            do {<br>                try await AuthorizationCenter.shared.requestAuthorization(for: .individual)<br>            } catch {<br>                print(error.localizedDescription)<br>            }<br>        }</pre><pre>AuthorizationCenter.shared.revokeAuthorization { result in<br>  // handle revoke<br>}</pre><p><strong>Device Activity</strong></p><p>In this article, I wanted to focus specifically on the Device Activity topic. When we examine the code section, we will see code pieces that are easy to understand and can be easily implemented. In order to monitor the relevant apps in Device Activity, we first need to select the relevant apps or categories using familyActivityPicker. The familyActivityPicker opens the screen you see in the picture and we can select an app or category from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*kgwxxbd2hfWQ7P1gO2SNjQ.png" /></figure><p>To open this screen, it will be sufficient to run the following code block.</p><pre>class ScreenTimeSelectAppsModel: ObservableObject {<br>    @Published var activitySelection = FamilyActivitySelection()<br><br>    init() { }<br>}<br><br>struct ScreenTimeSelectAppsContentView: View {<br><br>    @State private var pickerIsPresented = false<br>    @ObservedObject var model: ScreenTimeSelectAppsModel<br><br>    var body: some View {<br>        Button {<br>            pickerIsPresented = true<br>        } label: {<br>            Text(&quot;Select Apps&quot;)<br>        }<br>        .familyActivityPicker(<br>            isPresented: $pickerIsPresented,<br>            selection: $model.activitySelection<br>        )<br>    }<br>}</pre><p>When we examine the code, let’s first think that we created a data model. Its type should be FamilyActivitySelection. We can think that the selected selections will be stored here. We added a button to simulate it in the View section and showed the familyActivityPicker when the button is pressed. After making our selections here and dismissing the screen, the value of the FamilyActivitySelection object is updated, but it is not enough to update, we need to keep these selections on a device basis. These selections should not be deleted in subsequent openings of the app. We can do this by using user defaults.</p><pre> func setSelection(selection: FamilyActivitySelection) {<br>        let defaults = UserDefaults.standard<br>        defaults.set(try? encoder.encode(selection), forKey: userDefaultsKey)<br> }<br>    <br> func getSelection() -&gt; FamilyActivitySelection? {<br>        let defaults = UserDefaults.standard<br>        <br>        guard let data = defaults.data(forKey: userDefaultsKey) else { return nil }<br>        <br>        return defaults.decode(for: FamilyActivitySelection.self, using: userDefaultsKey)<br> }</pre><p>After completing all these operations, we now come to the app usage monitoring part. Before starting monitoring, we specify a schedule, that is, we say track and monitor this app at these time intervals. I have set 24 hours here, that is, I want this app to be monitored in 1-day periods.</p><pre>func getScheduleDeviceActivity() -&gt; DeviceActivitySchedule {<br>        return DeviceActivitySchedule(<br>            intervalStart: DateComponents(hour: 0, minute: 0, second: 0),<br>            intervalEnd: DateComponents(hour: 23, minute: 59, second: 59),<br>            repeats: true<br>        )<br>}</pre><p>After setting this, I determine a threshold value. For example, we can say that no more than 30 minutes should be spent on this app in 1 day.</p><pre>func startMonitoring() {<br>        let timeLimitMinutes = 30<br>        ....<br>}</pre><p>Then we create a DeviceActivityEvent object to start monitoring. We set the application, category, and webdomain tokens in the existing selection object and the 30-minute threshold value that I just determined for this event object. I start the process using the startMonitoring method in the DeviceActivityCenter. There are some parameters that the startMonitoring method requires. ActivityName and EventName are strings that you will specify completely. I also added the Schedule and event objects and started the monitoring process in the try-catch block here. By the way, the event name here should always be unique to that event. Because you can have more than one screen name event. In this way, I start monitoring. We can use the stopMonitoring method at the point where I want to stop.</p><pre> let selection: FamilyActivitySelection = getSelection() ?? FamilyActivitySelection()<br> let event = DeviceActivityEvent(<br>            applications: selection.applicationTokens,<br>            categories: selection.categoryTokens,<br>            webDomains: selection.webDomainTokens,<br>            threshold: DateComponents(minute: timeLimitMinutes))<br>        <br>let center = DeviceActivityCenter()<br>let activity = DeviceActivityName(&quot;MyApp.ScreenTime&quot;)<br>let eventName = DeviceActivityEvent.Name(&quot;MyApp.SomeEventName&quot;)<br>let schedule = getScheduleDeviceActivity()<br>        <br>do {<br>    try center.startMonitoring(<br>                activity,<br>                during: schedule,<br>                events: [eventName: event])<br>} catch { }</pre><p>After starting the monitor process, we can now inherit the DeviceActivityMonitor class and receive updates about the app’s screen time status thanks to the methods it provides us. One of these methods is eventDidReachThreshold. This method is triggered if the application reaches the threshold value you specify, that is, if the time that should be spent in the app has expired. And in this case, we can implement here whatever action we want to take.</p><pre>class MyMonitorExtension: DeviceActivityMonitor {<br>    override func eventDidReachThreshold(_ event: DeviceActivityEvent.Name, activity: DeviceActivityName) {<br>        super.eventDidReachThreshold(event, activity: activity)<br>        <br>        // Do something once the user has used their device too much.<br>    }<br>}</pre><p>This marks the end of this post so make sure to click on <strong>the clap button</strong>👏👏 if you liked it. See you in future posts…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1110751d2ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-nest/screen-time-api-d1110751d2ce">Screen Time API</a> was originally published in <a href="https://medium.com/ios-nest">iOS Nest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>