<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manish Yadav on Medium]]></title>
        <description><![CDATA[Stories by Manish Yadav on Medium]]></description>
        <link>https://medium.com/@manishdevstudio?source=rss-2cb23729549c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aCD7PnLHk4g7Tx5V0QxbjA.png</url>
            <title>Stories by Manish Yadav on Medium</title>
            <link>https://medium.com/@manishdevstudio?source=rss-2cb23729549c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:57:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manishdevstudio/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ GLM-4.5 & GLM-4.5 Air: Z.ai’s New Open-Source AI Powerhouses]]></title>
            <link>https://medium.com/@manishdevstudio/glm-4-5-glm-4-5-air-z-ais-new-open-source-ai-powerhouses-e749b292862c?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e749b292862c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source-ai-model]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 05:48:02 GMT</pubDate>
            <atom:updated>2025-08-01T05:48:02.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXV5Mhf_te9F4IAWQHrYJg.png" /><figcaption><strong>GLM‑4.5</strong> and <strong>GLM‑4.5 Air</strong></figcaption></figure><h3>🔍 Introduction</h3><p>In July 2025, Chinese AI startup <strong>Z.ai (formerly Zhipu AI)</strong> unveiled <strong>GLM‑4.5</strong> and <strong>GLM‑4.5 Air</strong>, two powerful <strong>open-source large language models</strong> designed for reasoning, coding, and agent-style tasks.<br>With <strong>355B</strong> and <strong>106B</strong> total parameters respectively, they’re not just big — they’re <strong>smart, efficient, and free to use</strong>.</p><p>These releases mark a major moment in the open-source AI race. 💡 As many closed models dominate the space, Z.ai is proving that <strong>open</strong> can also mean <strong>state-of-the-art</strong>.</p><h3>⚙️ Technical Specs at a Glance</h3><p>FeatureGLM‑4.5GLM‑4.5 Air🧠 Total Parameters355B106B🔄 Active Parameters32B12B🧠 ArchitectureMixture-of-Experts (MoE)Mixture-of-Experts (MoE)📜 Context Window128K tokens128K tokens⚡ GPU EfficiencyRuns on 8× H20 GPUsSuper lightweight🧩 Open SourceMIT (weights), Apache 2.0 (code)✅</p><h3>💡 What Makes It Special?</h3><ul><li>🧠 <strong>Mixture-of-Experts (MoE)</strong>: Scales intelligence without scaling compute.</li><li>🛠️ <strong>Built-in tool/function calling</strong>: No hacks — it’s native.</li><li>🧭 <strong>Agentic capabilities</strong>: Multi-step planning, decision-making, and external tool use.</li><li>📚 <strong>128K-token context</strong>: Huge window for long documents, codebases, or conversations.</li><li>⚡ <strong>Efficient &amp; fast</strong>: Trains on just 8 GPUs, super cost-effective.</li></ul><h3>📊 Benchmark Highlights</h3><ul><li>🥉 <strong>#3 globally</strong> across 12 major LLM benchmarks</li><li>🥇 <strong>#1 among open-source and Chinese models</strong></li><li>💬 <strong>BrowseComp benchmark</strong>: Beats Claude-4 Opus (26.4% vs 18.8%)</li><li>💻 <strong>SWE-Bench Verified</strong>: Solves 64.2% of real-world GitHub issues</li><li>🧪 <strong>Tool use accuracy</strong>: 90.6% — better than Claude &amp; Qwen3</li></ul><p>📈 <em>TL;DR: It competes with GPT-4 and Claude-4 on many real-world tasks.</em></p><h3>💸 Cost-Efficient &amp; Open</h3><ul><li>💰 <strong>API Pricing</strong>:</li><li>GLM‑4.5: From <strong>$0.60 / million input tokens</strong>, <strong>$2.20 / million output</strong></li><li>GLM‑4.5 Air: From <strong>$0.20 / million input</strong>, <strong>$1.10 / output</strong></li><li>🆓 <strong>Free and open-source</strong>:</li><li>✅ Weights: MIT License</li><li>✅ Code: Apache 2.0</li><li>✅ Available on Hugging Face and ModelScope</li></ul><h3>🔧 Deployment Options</h3><ul><li>🌐 Try it live at: <a href="https://chat.z.ai/">https://chat.z.ai</a></li><li>🔌 Compatible with OpenAI-style APIs</li><li>💾 Download and run locally via Hugging Face</li><li>🖥️ Self-host for full control and privacy</li></ul><h3>🌍 Impact on the AI Ecosystem</h3><p>GLM-4.5 signals a shift: <strong>open models are no longer second-best</strong>.<br>Z.ai’s move joins the likes of Qwen, DeepSeek, and Kimi — showing that <strong>China’s open-source AI game is strong</strong> and getting stronger.</p><p>📢 For developers, startups, and researchers:<br>No more waiting lists. No more black-box APIs. <strong>Just powerful models, ready to use.</strong></p><h3>🔚 Final Thoughts</h3><p>GLM‑4.5 and GLM‑4.5 Air are not just “another LLM” — they’re a <strong>statement</strong>.<br>That <strong>open, transparent, and efficient AI</strong> can match — or even beat — the closed giants.</p><p>🧠 Whether you’re building apps, coding agents, or exploring research, these models deserve a place in your toolkit.</p><p>📎 <strong>Try it now →</strong> <a href="https://z.ai/blog/glm-4.5">https://z.ai/blog/glm-4.5</a><br>📦 <strong>Download the models →</strong> Hugging Face</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e749b292862c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dark and Light Mode in React Native: A Modular Approach]]></title>
            <link>https://medium.com/@manishdevstudio/dark-and-light-mode-in-react-native-a-modular-approach-f64cf725098a?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f64cf725098a</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[dark-and-light-mode]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 11:19:32 GMT</pubDate>
            <atom:updated>2025-04-23T11:19:32.143Z</atom:updated>
            <content:encoded><![CDATA[<p>For implementing dark and light mode in React Native, I recommend using React’s Context API combined with a theming system. This approach is easy to implement, highly modular, and provides a clean way to manage themes throughout your application.</p><p>Here’s how to implement it:</p><h3>1. Create a Theme Context</h3><p>Start by creating a theme context that will hold your theme state and provide it throughout your app:</p><pre>// ThemeContext.js<br>import React, { createContext, useState, useEffect } from &#39;react&#39;;<br>import { useColorScheme } from &#39;react-native&#39;;<br><br>export const ThemeContext = createContext();<br><br>export const ThemeProvider = ({ children }) =&gt; {<br>  const deviceTheme = useColorScheme();<br>  const [isDarkMode, setIsDarkMode] = useState(deviceTheme === &#39;dark&#39;);<br><br>  // Track system theme changes<br>  useEffect(() =&gt; {<br>    setIsDarkMode(deviceTheme === &#39;dark&#39;);<br>  }, [deviceTheme]);<br><br>  // Toggle theme manually<br>  const toggleTheme = () =&gt; {<br>    setIsDarkMode(prevMode =&gt; !prevMode);<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ isDarkMode, toggleTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};</pre><h3>2. Define Theme Color Palettes</h3><p>Create a separate file for your theme colors:</p><pre>// theme.js<br>export const lightTheme = {<br>  background: &#39;#FFFFFF&#39;,<br>  text: &#39;#000000&#39;,<br>  primary: &#39;#007AFF&#39;,<br>  secondary: &#39;#5856D6&#39;,<br>  border: &#39;#E5E5EA&#39;,<br>  // Add more colors as needed<br>};<br><br>export const darkTheme = {<br>  background: &#39;#1C1C1E&#39;,<br>  text: &#39;#FFFFFF&#39;,<br>  primary: &#39;#0A84FF&#39;,<br>  secondary: &#39;#5E5CE6&#39;,<br>  border: &#39;#38383A&#39;,<br>  // Add more colors as needed<br>};</pre><h3>3. Create a Custom Hook for Easy Access</h3><pre>// useTheme.js<br>import { useContext } from &#39;react&#39;;<br>import { ThemeContext } from &#39;./ThemeContext&#39;;<br>import { lightTheme, darkTheme } from &#39;./theme&#39;;<br><br>export const useTheme = () =&gt; {<br>  const { isDarkMode, toggleTheme } = useContext(ThemeContext);<br>  const theme = isDarkMode ? darkTheme : lightTheme;<br>  <br>  return { theme, isDarkMode, toggleTheme };<br>};</pre><h3>4. Wrap Your App with the Theme Provider</h3><pre>// App.js<br>import React from &#39;react&#39;;<br>import { ThemeProvider } from &#39;./ThemeContext&#39;;<br>import MainApp from &#39;./MainApp&#39;;<br><br>export default function App() {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;MainApp /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>}</pre><h3>5. Use the Theme in Components</h3><pre>// SampleComponent.js<br>import React from &#39;react&#39;;<br>import { View, Text, TouchableOpacity, StyleSheet } from &#39;react-native&#39;;<br>import { useTheme } from &#39;./useTheme&#39;;<br><br>const SampleComponent = () =&gt; {<br>  const { theme, isDarkMode, toggleTheme } = useTheme();<br>  <br>  return (<br>    &lt;View style={[styles.container, { backgroundColor: theme.background }]}&gt;<br>      &lt;Text style={[styles.text, { color: theme.text }]}&gt;<br>        {isDarkMode ? &#39;Dark Mode&#39; : &#39;Light Mode&#39;} is active<br>      &lt;/Text&gt;<br>      &lt;TouchableOpacity<br>        style={[styles.button, { backgroundColor: theme.primary }]}<br>        onPress={toggleTheme}<br>      &gt;<br>        &lt;Text style={styles.buttonText}&gt;Toggle Theme&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>    padding: 20,<br>  },<br>  text: {<br>    fontSize: 18,<br>    marginBottom: 20,<br>  },<br>  button: {<br>    padding: 10,<br>    borderRadius: 5,<br>  },<br>  buttonText: {<br>    color: &#39;#FFFFFF&#39;,<br>  },<br>});<br><br>export default SampleComponent;</pre><h3>Advanced Features to Consider</h3><ol><li><strong>Persistence</strong>: Save the user’s theme preference using AsyncStorage:</li></ol><pre>// Enhanced ThemeProvider with persistence<br>import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;<br><br>// In ThemeProvider<br>useEffect(() =&gt; {<br>  const loadTheme = async () =&gt; {<br>    try {<br>      const savedTheme = await AsyncStorage.getItem(&#39;userThemePreference&#39;);<br>      if (savedTheme !== null) {<br>        setIsDarkMode(savedTheme === &#39;dark&#39;);<br>      } else {<br>        setIsDarkMode(deviceTheme === &#39;dark&#39;);<br>      }<br>    } catch (e) {<br>      console.error(&#39;Failed to load theme preference&#39;);<br>    }<br>  };<br>  <br>  loadTheme();<br>}, []);<br><br>const toggleTheme = async () =&gt; {<br>  const newTheme = !isDarkMode;<br>  setIsDarkMode(newTheme);<br>  try {<br>    await AsyncStorage.setItem(&#39;userThemePreference&#39;, newTheme ? &#39;dark&#39; : &#39;light&#39;);<br>  } catch (e) {<br>    console.error(&#39;Failed to save theme preference&#39;);<br>  }<br>};</pre><p><strong>2. System Theme Syncing Option</strong>: Let users choose between manual or system theme:</p><pre>// Add to ThemeProvider<br>const [syncWithSystem, setSyncWithSystem] = useState(true);<br><br>useEffect(() =&gt; {<br>  if (syncWithSystem) {<br>    setIsDarkMode(deviceTheme === &#39;dark&#39;);<br>  }<br>}, [deviceTheme, syncWithSystem]);<br><br>const toggleSystemSync = (value) =&gt; {<br>  setSyncWithSystem(value);<br>  // Save preference to AsyncStorage<br>};</pre><p>This approach provides a clean, modular way to implement theming that’s easy to extend and maintain. The separation of concerns makes it simple to add new theme options beyond just dark and light if desired.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f64cf725098a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Animations in React Native: From Basics to Advanced Technique]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-animations-in-react-native-from-basics-to-advanced-technique-2e2e1a8393df?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e2e1a8393df</guid>
            <category><![CDATA[mobile-ui]]></category>
            <category><![CDATA[reanimation]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[animated-api]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 07:01:08 GMT</pubDate>
            <atom:updated>2025-03-19T07:01:08.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JAFFNHf2DkW_ElFkNEuqw.png" /></figure><h4>Introduction</h4><p>Imagine your React Native app coming to life — buttons that fade in with a gentle glow, screens that glide seamlessly, and elements that dance with every tap. Animations can transform your app into a <strong>smooth, modern, and responsive</strong> experience. Yet, crafting them effectively can feel like wrestling with a wild beast. Fear not! Today, we’ll journey from the basics to advanced techniques, unlocking the secrets to make your app dazzle. Let’s get started! ✨</p><h4>🔍 Why Animations Matter</h4><p>Animations aren’t just eye candy — they’re the heartbeat of a great user experience. They:</p><ul><li><strong>Guide users</strong> with visual feedback, like a button pulsing to confirm a tap.</li><li><strong>Smooth transitions</strong>, making screen changes feel effortless and natural.</li><li><strong>Elevate polish</strong>, giving your app that pro-level sheen.</li></ul><p>But beware: sloppy animations can stutter, lag, or drain performance. Our mission? Master the craft and keep things silky smooth. 💪</p><h4>📖 Getting Started with React Native Animations</h4><p>React Native offers two powerhouse tools for animations:</p><ol><li><strong>Animated API</strong> — Built-in, perfect for simple, interruptible effects like fades or slides.</li><li><strong>Reanimated Library</strong> — A third-party gem (now at version 3 in 2025), delivering precision and performance for complex interactions.</li></ol><p>Let’s dive into both, hands-on. 👇</p><h4>✅ Mastering the Animated API</h4><p>The Animated API is your go-to for quick, elegant animations — think fade-ins, zooms, or gentle shifts. It’s lightweight and runs smoothly with the right setup.</p><p><strong>Example:</strong> A welcoming fade-in effect.</p><pre>import React, { useRef, useEffect } from &#39;react&#39;;<br>import { Animated, View, Text, StyleSheet } from &#39;react-native&#39;;<br><br>const FadeInComponent = () =&gt; {<br>  const fadeAnim = useRef(new Animated.Value(0)).current; // Start invisible<br><br>  useEffect(() =&gt; {<br>    Animated.timing(fadeAnim, {<br>      toValue: 1,          // Fade to full opacity<br>      duration: 1000,      // 1 second<br>      useNativeDriver: true, // Boost performance<br>    }).start();<br>  }, [fadeAnim]);<br><br>  return (<br>    &lt;Animated.View style={[styles.fadingContainer, { opacity: fadeAnim }]}&gt;<br>      &lt;Text style={styles.fadingText}&gt;Welcome to React Native Animations!&lt;/Text&gt;<br>    &lt;/Animated.View&gt;<br>  );<br>};<br><br>const styles = StyleSheet.create({<br>  fadingContainer: {<br>    padding: 20,<br>    backgroundColor: &#39;#87CEEB&#39;, // Skyblue<br>    borderRadius: 8,<br>  },<br>  fadingText: {<br>    fontSize: 24,<br>    fontWeight: &#39;bold&#39;,<br>    textAlign: &#39;center&#39;,<br>    color: &#39;#333&#39;,<br>  },<br>});<br><br>export default FadeInComponent;</pre><p>Run this, and watch the text bloom into view like a sunrise. 🌅</p><p>📌 <strong>Pro Tip:</strong> Always set useNativeDriver: true to offload work to the native thread, avoiding janky frames.</p><h4>✅ Unleashing Reanimated 3</h4><p>Reanimated 3 (the latest as of March 2025) is a game-changer. It runs animations natively, supports the new Fabric architecture, and offers a declarative API for everything from simple bounces to intricate gestures. It’s the choice for pros tackling complex interactions.</p><p><strong>Example:</strong> A draggable box that snaps back with flair.</p><pre>import React from &#39;react&#39;;<br>import { View, StyleSheet, Dimensions } from &#39;react-native&#39;;<br>import { PanGestureHandler } from &#39;react-native-gesture-handler&#39;; // Correct import<br>import Animated, {<br>  useSharedValue,<br>  useAnimatedStyle,<br>  useAnimatedGestureHandler,<br>  withSpring,<br>} from &#39;react-native-reanimated&#39;;<br><br>const { width, height } = Dimensions.get(&#39;window&#39;);<br><br>const DraggableBox = () =&gt; {<br>  const startX = (width - 100) / 2; // Center horizontally<br>  const startY = (height - 100) / 2; // Center vertically<br>  const posX = useSharedValue(startX);<br>  const posY = useSharedValue(startY);<br><br>  const onGesture = useAnimatedGestureHandler({<br>    onActive: (event) =&gt; {<br>      posX.value = startX + event.translationX;<br>      posY.value = startY + event.translationY;<br>    },<br>    onEnd: () =&gt; {<br>      posX.value = withSpring(startX, { damping: 10 }); // Snap back<br>      posY.value = withSpring(startY, { damping: 10 });<br>    },<br>  });<br><br>  const animatedStyle = useAnimatedStyle(() =&gt; ({<br>    transform: [{ translateX: posX.value }, { translateY: posY.value }],<br>  }));<br><br>  return (<br>    &lt;PanGestureHandler onGestureEvent={onGesture}&gt;<br>      &lt;Animated.View style={[styles.box, animatedStyle]} /&gt;<br>    &lt;/PanGestureHandler&gt;<br>  );<br>};<br><br>const styles = StyleSheet.create({<br>  box: {<br>    width: 100,<br>    height: 100,<br>    backgroundColor: &#39;#FF6347&#39;, // Tomato<br>    borderRadius: 12,<br>    shadowColor: &#39;#000&#39;,<br>    shadowOffset: { width: 0, height: 2 },<br>    shadowOpacity: 0.3,<br>    shadowRadius: 4,<br>  },<br>});<br><br>export default DraggableBox;</pre><p>Drag the box around — it’s buttery smooth. Release it, and it springs back to center with a playful bounce. 🎉</p><p>📌 <strong>Pro Tip:</strong> useSharedValue outperforms React state for animations, keeping updates native and fast. Note: Install react-native-gesture-handler alongside Reanimated for gestures to work.</p><h4>🔧 Advanced Techniques to Wow Your Users</h4><p>Ready to level up? Here’s how to push animations further:</p><ol><li><strong>Combining Animations</strong><br>Chain fades with slides using Animated.sequence or run them together with Animated.parallel. Reanimated’s withDecay adds physics-like flair.</li><li><strong>Gesture-Driven Magic</strong><br>Pair Reanimated with Gesture Handler for swipeable cards or pinch-to-zoom effects. The draggable box above is just the start!</li><li><strong>LayoutAnimation for Simplicity</strong><br>Automatically animate layout changes — like expanding a card — with this built-in API. Try this:</li></ol><pre>import { LayoutAnimation, TouchableOpacity, View, Text } from &#39;react-native&#39;;<br>const toggle = () =&gt; {<br>  LayoutAnimation.easeInEaseOut();<br>  setExpanded(!expanded);<br>};</pre><p>Caveat: It’s less consistent on Android, so test thoroughly.</p><p>4.<strong> Custom Animations with Reanimated</strong><br>Use useAnimatedStyle and custom easing curves (e.g., Easing.bezier) to craft unique effects tailored to your app’s vibe.</p><p>Explore more in the <a href="https://docs.swmansion.com/react-native-reanimated/">Reanimated Docs</a> or <a href="https://reactnative.dev/docs/animations">React Native Animations Guide</a>.</p><h4>🚀 Performance Hacks</h4><ul><li><strong>Animated API:</strong> Stick to useNativeDriver for 60FPS bliss.</li><li><strong>Reanimated:</strong> It’s native by default — perfect for heavy lifting. Plus, version 3 supports Fabric, future-proofing your app.</li><li><strong>Debugging:</strong> Use React Native Debugger to spot frame drops.</li></ul><h4>📌 Conclusion</h4><p>Animations are your secret weapon to craft delightful React Native apps. With the Animated API, you’ll nail the basics. With Reanimated 3, you’ll conquer the complex. Together, they’ll make your UI sing — smooth, responsive, and downright gorgeous. 🌟</p><p>What’s your favorite animation trick? Drop it in the comments — I’d love to hear your hacks! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e2e1a8393df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your React Native App’s Speed: Stop Unnecessary Re-renders ]]></title>
            <link>https://medium.com/@manishdevstudio/boost-your-react-native-apps-speed-stop-unnecessary-re-renders-d5872072cd84?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5872072cd84</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[react-memo]]></category>
            <category><![CDATA[memorization]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 06:19:19 GMT</pubDate>
            <atom:updated>2025-03-19T06:19:19.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*Mmtt0QaWjw4rj5bePgdn_Q.png" /></figure><p><strong>Introduction</strong><br>Are you frustrated with your React Native app feeling slow and unresponsive? The culprit is often unnecessary re-renders! These performance bottlenecks can make your app sluggish and drive users away. Let’s dive into why unnecessary re-renders happen and how to fix them for a super-smooth experience. 💨</p><p>❓<strong> Why Do Unnecessary Re-renders Happen?</strong><br>React Native components re-render when their props or state change. But here’s the catch — inefficient state management or misuse of context can trigger these re-renders unnecessarily.</p><p>Common reasons for unnecessary re-renders include:<br>1. 🔄 Frequently updating parent component states.<br>2. 📣 Passing anonymous functions as props.<br>3. ❌ Not using `React.memo()` or `useCallback()` properly.<br>4. 🎨 Using inline styles within components.</p><p>But don’t worry! We’ve got the fixes you need. 👇</p><p><strong>💡 How to Prevent Unnecessary Re-renders</strong><br>Here are some killer techniques to boost your app’s performance:</p><p>✅<strong> 1. Leverage `React.memo()` for Functional Components</strong><br>Wrapping functional components with `<strong>React.memo()</strong>` can stop them from re-rendering unless their props actually change.</p><p><strong>Example:</strong></p><pre>import React, { memo } from &#39;react&#39;;<br><br>const MyComponent = ({ text }) =&gt; {<br>  console.log(&#39;Rendered&#39;);<br>  return &lt;Text&gt;{text}&lt;/Text&gt;;<br>};<br><br>export default memo(MyComponent);</pre><p>📌<strong> Pro Tip:</strong> Only use `<strong>React.memo()</strong>` for components that re-render with the same props most of the time.</p><p>✅ <strong>2. Utilize `useCallback()` for Functions Passed as Props</strong><br>Functions declared within a component get recreated on every render. Wrapping them with `<strong>useCallback()</strong>` helps to prevent this.</p><p><strong>Example:</strong></p><pre>import React, { useCallback, useState } from &#39;react&#39;;<br>import { Button, Text } from &#39;react-native&#39;;<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  const increment = useCallback(() =&gt; {<br>    setCount(prev =&gt; prev + 1);<br>  }, []);<br><br>  return (<br>    &lt;Button title={`Count: ${count}`} onPress={increment} /&gt;<br>  );<br>};<br><br>export default Counter;</pre><p>📌 <strong>Pro Tip:</strong> Use `<strong>useCallback()</strong>` only when passing functions as props to prevent unnecessary renders.</p><p>✅<strong> 3. Avoid Inline Styles</strong><br>Creating styles within render methods forces React Native to recreate the style objects on every render. Extract them to a `<strong>StyleSheet</strong>` instead.</p><p><strong>Bad Practice:</strong></p><pre>&lt;View style={{ margin: 10, padding: 5 }} /&gt;</pre><p><strong>Good Practice:</strong></p><pre>const styles = StyleSheet.create({<br> box: {<br> margin: 10,<br> padding: 5,<br> },<br>});<br>&lt;View style={styles.box} /&gt;</pre><p>📌 <strong>Pro Tip:</strong> Always define styles outside the component’s render method for better performance.</p><p>✅<strong> 4. Prefer `FlatList` Over `.map()` Rendering</strong><br>Rendering arrays with `<strong>.map()`</strong> may seem straightforward but it isn’t optimized for performance. Instead, use `<strong>FlatList</strong>` for rendering large lists efficiently.</p><pre>&lt;FlatList<br> data={items}<br> keyExtractor={(item) =&gt; item.id.toString()}<br> renderItem={({ item }) =&gt; &lt;Text&gt;{item.name}&lt;/Text&gt;}<br>/&gt;</pre><p><strong>📌 Pro Tip:</strong> Implement `getItemLayout` and `initialNumToRender` for better performance in large lists.</p><p><strong>📌 Conclusion</strong><br>By optimizing re-renders, your React Native app can run faster and feel snappier. Apply techniques like <strong>`React.memo()`, `useCallback()`</strong>, avoiding inline styles, and using <strong>`FlatList`</strong> to achieve peak performance. Try them out and see the difference! 💪🔥</p><p>What optimization techniques do you use in your React Native apps? Share your thoughts below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5872072cd84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift Magic: Generics, Protocols, and Extensions]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-swift-magic-generics-protocols-and-extensions-144aaaef155c?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/144aaaef155c</guid>
            <category><![CDATA[swift-extensions]]></category>
            <category><![CDATA[swift-protocol]]></category>
            <category><![CDATA[swift-generic-types]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 04:45:37 GMT</pubDate>
            <atom:updated>2025-03-18T04:47:55.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IJkI-t8CBNNIDJf7upZBw.png" /></figure><p>Swift is known for its elegant syntax, powerful type system, and modern approach to programming. While most developers are familiar with the basics of Swift, mastering advanced features like **Generics**, **Protocols**, and **Extensions** can elevate your code to the next level. In this article, we’ll dive deep into these concepts, exploring how they work and how to harness their full potential — all while keeping things fun! 🚀</p><h4>Generics: Writing Flexible and Reusable Code</h4><p>Generics allow you to write flexible, reusable functions and types that can work with any type, subject to certain constraints. Think of them as the shape-shifters of the Swift world! They provide powerful tools to avoid code duplication and write cleaner, type-safe code.</p><p><strong>Example: The Magic Swap Spell 🔄</strong><br>Imagine a wizard swapping two objects, regardless of what they are:</p><pre>func swapValues&lt;T&gt;(_ a: inout T, _ b: inout T) {<br> let temp = a<br> a = b<br> b = temp<br>}<br>var health = 100<br>var mana = 50<br>swapValues(&amp;health, &amp;mana)<br>print(&quot;Health: \(health), Mana: \(mana)&quot;) // Output: Health: 50, Mana: 100</pre><p>This magical spell, `swapValues`, works on any type you throw at it — be it `Int`, `String`, or even your custom `Wizard` struct!</p><p><strong>Generic Types: The Potion Stack 🧪</strong><br>A stack is a perfect use case for generics. Let’s say you’re building a game where you can store potions of various kinds:</p><pre>struct Stack&lt;Element&gt; {<br> private var elements: [Element] = []<br>mutating func push(_ element: Element) {<br> elements.append(element)<br> }<br>mutating func pop() -&gt; Element? {<br> return elements.popLast()<br> }<br>}<br>var potionStack = Stack&lt;String&gt;()<br>potionStack.push(&quot;Healing Potion&quot;)<br>potionStack.push(&quot;Mana Potion&quot;)<br>print(potionStack.pop() ?? &quot;No potion left!&quot;) // Output: Mana Potion<br></pre><p>Your potion inventory is now dynamic and type-safe!</p><h4>Protocols: Defining Requirements</h4><p>Protocols provide a blueprint for methods, properties, and other requirements that suit a particular task or piece of functionality. Think of them as contracts that must be fulfilled.</p><p><strong>Example: The Drawable Army ⚔️</strong><br>In your fantasy game, you want different entities to be drawable. Enter the `Drawable` protocol:</p><pre>protocol Drawable {<br>    func draw() -&gt; String<br>}<br><br>struct Warrior: Drawable {<br>    func draw() -&gt; String {<br>        return &quot;Drawing a brave Warrior!&quot;<br>    }<br>}<br><br>struct Dragon: Drawable {<br>    func draw() -&gt; String {<br>        return &quot;Drawing a fearsome Dragon!&quot;<br>    }<br>}<br><br>func summonCreature(_ creature: Drawable) {<br>    print(creature.draw())<br>}<br><br>summonCreature(Warrior())   // Output: Drawing a brave Warrior!<br>summonCreature(Dragon())    // Output: Drawing a fearsome Dragon!</pre><p>Protocols bring structure and creativity to your kingdom’s codebase.</p><h4><strong>Extensions: Enhancing Existing Types</strong></h4><p>Extensions are your magic wands for adding new abilities to existing types without subclassing or altering original code.</p><p><strong>Example: The Int Spellbook 📚</strong><br>Let’s enhance `Int` with a cool spell-casting method:</p><pre>extension Int {<br> func castSpell() -&gt; String {<br> switch self {<br> case 1: return &quot;Fireball! 🔥&quot;<br> case 2: return &quot;Ice Blast! ❄️&quot;<br> case 3: return &quot;Lightning Strike! ⚡️&quot;<br> default: return &quot;Unknown Spell…&quot;<br> }<br> }<br>}<br>let spell = 2<br>print(spell.castSpell()) // Output: Ice Blast! ❄️</pre><p>Extensions are amazing for customizing standard types or even third-party libraries to fit your needs.</p><p><strong>Putting It All Together: The Ultimate Cache System 🔒</strong><br>Let’s say you need a generic caching system for your game to store various items like images, user data, or game progress.</p><pre>protocol Cacheable {<br> associatedtype DataType<br> func save(_ data: DataType)<br> func load() -&gt; DataType?<br>}<br>class DiskCache&lt;T&gt;: Cacheable {<br> private var storage: T?<br>func save(_ data: T) {<br> storage = data<br> }<br>func load() -&gt; T? {<br> return storage<br> }<br>}<br>var stringCache = DiskCache&lt;String&gt;()<br>stringCache.save(&quot;Epic Sword&quot;)<br>print(stringCache.load() ?? &quot;No item found&quot;) // Output: Epic Sword<br>var intCache = DiskCache&lt;Int&gt;()<br>intCache.save(42)<br>print(intCache.load() ?? 0) // Output: 42</pre><p><strong>Conclusion</strong><br>Swift’s powerful features such as <strong>Generics, Protocols,</strong> and <strong>Extensions</strong> allow you to write elegant, reusable, and highly modularized code. Whether you’re building games, apps, or APIs, mastering these features will take your skills to the next level. So, go ahead and experiment with these tools — let your code shine! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=144aaaef155c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift 6: New Features and How to Use Them Effectively]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-swift-6-new-features-and-how-to-use-them-effectively-6ed03752e6d4?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed03752e6d4</guid>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 12:13:50 GMT</pubDate>
            <atom:updated>2025-03-17T12:13:50.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEBOIIeuycBQJ7Ero9pCZg.png" /></figure><h4><strong>Key Points</strong></h4><ul><li>Swift 6, released in September 2024, introduces significant new features for safer concurrency, better error handling, and improved performance.</li><li>It seems likely that these updates, such as data-race safety and typed throws, will enhance developer productivity and code reliability.</li><li>Research suggests that the expanded C++ interoperability and embedded Swift subset could broaden Swift’s use in diverse fields like embedded systems and cross-platform development.</li></ul><h4>Swift 6 Overview</h4><p>Swift 6 is a major update to the Swift programming language, announced in September 2024 and now widely available by March 2025. It focuses on enhancing safety, performance, and developer experience, particularly in concurrent programming, error handling, and cross-platform support.</p><h4>New Features and Benefits</h4><ul><li><strong>Concurrency Safety</strong>: Swift 6 introduces data-race safety, an opt-in feature that catches potential data races at compile time, making concurrent code more reliable. For example, using actors ensures only one task accesses shared mutable state at a time, preventing bugs.</li><li><strong>Improved Error Handling</strong>: Typed throws allow functions to specify exact error types, improving clarity and safety in generic code. This means developers can handle errors more precisely, reducing runtime surprises.</li><li><strong>Performance Enhancements</strong>: Support for non-copyable types in generics and new 128-bit integer types boost performance, especially for resource-heavy applications like scientific computing.</li></ul><h4>Unexpected Detail: Embedded Systems Support</h4><p>An unexpected benefit is the introduction of Embedded Swift, a subset for resource-constrained environments like IoT devices, supporting ARM and RISC-V bare-metal targets. This opens Swift to new domains, potentially revolutionizing development in embedded systems.</p><h4>Survey Note: Detailed Analysis of Swift 6 New Features</h4><p>Swift 6, announced on <a href="https://www.swift.org/blog/announcing-swift-6/">Swift.org — Announcing Swift 6</a> in September 2024, marks a significant evolution in the Swift programming language, enhancing its capabilities for safety, performance, and cross-platform development. Given the current date, March 17, 2025, Swift 6 has been in use for several months, and its impact is becoming evident in developer communities. This section provides a comprehensive exploration of its new features, drawing from official documentation and community insights, to offer a thorough understanding for developers and enthusiasts.</p><h4>Concurrency Improvements</h4><p>One of the standout features is data-race safety, an opt-in language mode that extends Swift’s safety guarantees to prevent data races in concurrent code. Data races occur when multiple threads access shared mutable state without proper synchronization, leading to unpredictable behavior. In Swift 6, this is addressed by diagnosing potential data races as compiler errors, a step up from the warnings in Swift 5.10 with the -strict-concurrency=complete flag. Improved Sendable inference and new compiler analysis for mutable state transfer further enhance this, with migration guidance available at <a href="http://swift.org/migration">Swift.org/migration</a>.</p><p>For example, consider a counter class prone to data races in earlier versions:</p><pre>class Counter {<br>    var value = 0<br>    func increment() {<br>        value += 1<br>    }<br>}</pre><p>In Swift 6, transforming it into an actor ensures serialized access:</p><pre>actor Counter {<br>    var value = 0<br>    func increment() {<br>        value += 1<br>    }<br>}</pre><p>Usage requires <strong>await</strong>, ensuring safety:</p><pre>let counter = Counter()<br>Task {<br>    await counter.increment()<br>}</pre><p>Additionally, a new synchronization library provides low-level concurrency APIs, including atomic operations and mutexes, detailed at <a href="https://developer.apple.com/documentation/synchronization">Apple Developer — Synchronization</a>.</p><h4>Error Handling with Typed Throws</h4><p>Typed throws, another significant addition, allow functions to specify the error type in their signature, enhancing type safety in generic code and resource-constrained environments like Embedded Swift. For instance:</p><pre>enum ParseError: Error {<br>    case invalidFormat<br>}<br><br>func parseInt(_ s: String) throws(ParseError) -&gt; Int {<br>    if let num = Int(s) {<br>        return num<br>    } else {<br>        throw ParseError.invalidFormat<br>    }<br>}</pre><p>This contrasts with Swift 5’s throws keyword, which accepts any Error type. The typed approach, generalizing over throws(any Error) and throws(Never), enables precise error handling, as shown:</p><pre>do {<br>    let number = try parseInt(&quot;123&quot;)<br>    print(number)<br>} catch ParseError.invalidFormat {<br>    print(&quot;Invalid format&quot;)<br>}</pre><p>This feature is particularly useful in generic programming, ensuring developers handle specific error types, reducing runtime errors.</p><h4>Ownership and Performance</h4><p>Swift 6 enhances support for non-copyable types in generics, a critical advancement for performance and correctness. Non-copyable types, marked with ~Copyable, cannot be copied, making them ideal for unique ownership scenarios like file handles or resource management. This is supported in generics, allowing both copyable and non-copyable types, benefiting copy-on-write containers like Array and Dictionary.</p><p>For example, define a non-copyable type:</p><pre>struct UniqueResource: ~Copyable {<br>    let id: Int<br>    init(_ id: Int) {<br>        self.id = id<br>    }<br>}</pre><p>A generic function can then work with it:</p><pre>func process&lt;T: ~Copyable&gt;(resource: T) {<br>    // Process resource<br>}</pre><p>Usage:</p><pre>let resource = UniqueResource(1)<br>process(resource: resource)</pre><p>This feature, detailed in <a href="https://www.hackingwithswift.com/swift/6.0/noncopyable-upgrades">Hacking with Swift — Noncopyable Upgrades</a>, also supports types like Atomic, Optional, and Result, enhancing performance in performance-critical applications.</p><p>Additionally, 128-bit integer types (Int128 and UInt128), available on all platforms, cater to applications requiring high-precision arithmetic, such as cryptography or financial calculations. Example usage:</p><pre>let a: Int128 = 12345678901234567890<br>let b: Int128 = 98765432109876543210<br>let sum = a + b<br>print(sum)</pre><p>This is documented at <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0425-int128.md">Swift Evolution — Int128 Proposal</a>.</p><h4>C++ Interoperability</h4><p>Expanded C++ support in Swift 6 includes move-only types, virtual methods, default arguments, and standard library components like std::map and std::optional. This is crucial for projects integrating Swift and C++, especially in performance-critical areas. Non-copyable types (~Copyable) align with C++ move semantics, and annotations like SWIFT_SHARED_REFERENCE and SWIFT_IMMORTAL_REFERENCE handle virtual methods efficiently. This feature, while advanced, broadens Swift’s applicability in mixed-language environments.</p><h4>Embedded Swift</h4><p>Embedded Swift, a language subset for embedded systems, supports ARM and RISC-V bare-metal targets, producing small binaries without runtime or type metadata. This is experimental, with ongoing development at <a href="https://github.com/swiftlang/swift-evolution/blob/main/visions/embedded-swift.md">Swift Evolution — Embedded Swift Vision</a>, opening Swift to IoT, robotics, and other resource-constrained domains.</p><h4>Productivity Enhancements</h4><p>Several features enhance developer productivity:</p><ul><li>count(where:): Counts elements in a collection satisfying a condition, e.g., let count = [1, 2, 3, 4].count(where: { $0 &gt; 2 }) // Returns 2.</li><li>Pack iteration: Allows iterating over tuple elements in for-loops, enhancing tuple handling.</li><li>Import access control: Controls module accessibility, improving encapsulation.</li><li>Macro improvements: Include @attached(body) macros and expression macros as default arguments, detailed at <a href="https://www.swift.org/swift-evolution/#?version=6.0">Swift Evolution Dashboard</a>.</li></ul><p>These features, while smaller, streamline development, making Swift more efficient for everyday coding tasks.</p><h4>Debugging Improvements</h4><p>The @DebugDescription macro customizes debugger output, enhancing visibility during debugging. For example:</p><pre>struct Person {<br>    let name: String<br>    let age: Int<br>    @DebugDescription var debugDescription: String {<br>        return &quot;Person(name: \(name), age: \(age))&quot;<br>    }<br>}</pre><p>Improved startup performance for debuggers, avoiding recompiling Clang modules, reduces header import issues, detailed at <a href="https://developer.apple.com/documentation/swift/debugdescription/">Apple Developer — DebugDescription</a>.</p><h4>Library Updates</h4><ul><li><strong>Foundation Unification</strong>: Reimplemented core types (JSONDecoder, URL, etc.) in Swift, unified across platforms, open source, available on macOS 15, iOS 18, Linux, Windows. New APIs include Expression, calendar improvements, and FormatStyle enhancements, with FoundationEssentials for binary size optimization.</li><li><strong>Swift Testing Library</strong>: Offers expressive APIs and macro support (@Test, @Suite, #expect, #require), scaling with parameterization, included in toolchains, supporting all Swift platforms, at <a href="https://github.com/swiftlang/swift-testing">Swift Testing GitHub</a> and forums at <a href="https://forums.swift.org/c/related-projects/swift-testing/103">Swift Forums — Swift Testing</a>.</li></ul><h4>Platform Support</h4><ul><li><strong>Fully Static SDK for Linux</strong>: Builds statically linked executables, no external dependencies, cross-compile support, at <a href="https://www.swift.org/documentation/articles/static-linux-getting-started.html">Swift.org — Static Linux Getting Started</a>.</li><li><strong>New Linux Distributions</strong>: Official support for Debian, Fedora, Ubuntu 24.04.</li><li><strong>Windows Build Performance</strong>: Prebuilt toolchains for arm64, package manager parallelizes builds, up to 10x faster on 10-core machines.</li></ul><p>These enhancements, summarized in the table below, expand Swift’s reach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Embb_S8Wg7txO8E93KaVsw.png" /></figure><p>Download Swift 6 at <a href="https://www.swift.org/install">Swift.org — Install</a>, learn more at <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/">The Swift Programming Language book</a>.</p><p>This comprehensive update positions Swift 6 as a robust choice for modern development, with features catering to a wide range of applications, from mobile apps to embedded systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed03752e6d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Apple’s Screen Time API (Part 4): Visualizing and Managing Activity Data]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-apples-screen-time-api-part-4-visualizing-and-managing-activity-data-a761a8daed55?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a761a8daed55</guid>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 07:48:19 GMT</pubDate>
            <atom:updated>2025-03-13T07:48:19.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1crjXa5lFlj_uyu095G4zA.png" /></figure><p>Welcome back to our in-depth exploration of Apple’s Screen Time API! So far, we’ve covered the fundamentals — setting up time limits and monitoring app usage. Now, in Part 4, we’ll tackle one of the most exciting and valuable aspects: **visualizing and managing activity data** through Apple’s powerful **Device Activity Report extension**.</p><p>Why is this important? Because presenting usage data in a clear, interactive format transforms raw information into something meaningful. Whether you’re a parent monitoring your child’s digital habits or an individual aiming to better understand your screen time patterns, this feature is your key to turning data into insights.</p><p>— -</p><p><strong>## 📌 What is the Device Activity Report Extension?</strong></p><p>Apple’s **Device Activity framework** offers a specialized extension point known as `DeviceActivityReportExtension`. This tool allows developers to generate custom reports based on collected screen time data. With it, you can:</p><p>✅ <strong>Data Retrieval</strong>: Access detailed usage stats for apps and categories.<br>✅ <strong>Custom Visuals</strong>: Build tailored UIs to display trends and patterns.<br>✅ <strong>Privacy Focus</strong>: Process everything on-device, respecting user control.<br>✅ <strong>Insight Generation</strong>: Analyze historical data for meaningful takeaways</p><p>Now, let’s dive into implementing this powerful feature in your SwiftUI app!</p><p>— -</p><p><strong>## 🔨 Setting Up the Device Activity Report Extension</strong></p><p>The first step is to add a new target to your Xcode project for the report extension. Follow these steps:</p><ul><li>Go to <strong>File &gt; New &gt; Target</strong> in Xcode.</li><li>Choose <strong>Device Activity Report Extension</strong> under the iOS tab.</li><li>Name it (e.g., “ScreenTimeReportExtension”) and embed it in your main app.</li></ul><p>4. Ensure it’s embedded in your main application.</p><p>Now, configure your `Info.plist` file by adding the following keys:</p><pre>&lt;key&gt;DeviceActivityReportExtensionCategories&lt;/key&gt;<br>&lt;array&gt;<br> &lt;string&gt;daily&lt;/string&gt;<br> &lt;string&gt;weekly&lt;/string&gt;<br>&lt;/array&gt;<br></pre><p>This setup specifies the reporting periods your extension will support.</p><p>— -</p><p><strong>## 💡 Implementing the Device Activity Report Extension</strong></p><p>At the core of your extension is a class conforming to the `DeviceActivityReportExtension` protocol. Here’s a basic implementation:</p><pre>import DeviceActivity<br>import SwiftUI<br><br>class ScreenTimeReportExtension: NSObject, DeviceActivityReportExtension {<br>    func report(for context: DeviceActivityReport.Context) -&gt; some DeviceActivityReportScene {<br>        switch context.categoryToken {<br>        case &quot;daily&quot;:<br>            return DailyReportView(context: context)<br>        case &quot;weekly&quot;:<br>            return WeeklyReportView(context: context)<br>        default:<br>            return EmptyReportView()<br>        }<br>    }<br>}<br><br>struct EmptyReportView: DeviceActivityReportScene {<br>    let context: DeviceActivityReport.Context<br>    <br>    var body: some View {<br>        Text(&quot;No report available&quot;)<br>    }<br>}</pre><ul><li>The report(for:) method returns a SwiftUI view based on the report type (daily or weekly).</li><li>We’ve added a fallback EmptyReportView for unsupported contexts.</li></ul><p>This is the backbone — next, we’ll flesh it out with custom report views.</p><p>— -</p><p><strong>## Building the Daily Report View</strong></p><p>To make our data visually appealing, let’s build a simple SwiftUI view to display daily usage:</p><pre>import DeviceActivity<br>import SwiftUI<br><br>struct DailyReportView: DeviceActivityReportScene {<br>    let context: DeviceActivityReport.Context<br>    <br>    @State private var appUsageData: [AppUsageData] = []<br>    @State private var selectedApp: String?<br>    <br>    var body: some View {<br>        NavigationStack {<br>            VStack(spacing: 20) {<br>                Text(&quot;Today’s App Usage&quot;)<br>                    .font(.title2.bold())<br>                <br>                if appUsageData.isEmpty {<br>                    ProgressView(&quot;Loading...&quot;)<br>                } else {<br>                    UsagePieChartView(data: appUsageData, selectedApp: $selectedApp)<br>                        .frame(height: 250)<br>                    <br>                    List(appUsageData, id: \.appName) { app in<br>                        AppUsageRow(app: app, isSelected: app.appName == selectedApp)<br>                            .onTapGesture {<br>                                selectedApp = app.appName<br>                            }<br>                    }<br>                    .listStyle(.plain)<br>                }<br>            }<br>            .padding()<br>            .task {<br>                await loadActivityData()<br>            }<br>        }<br>    }<br>    <br>    private func loadActivityData() async {<br>        do {<br>            let center = DeviceActivityCenter()<br>            let data = try await center.activityReport(for: context)<br>            appUsageData = processActivityData(data)<br>        } catch {<br>            print(&quot;Failed to load activity data: \(error)&quot;)<br>        }<br>    }<br>    <br>    private func processActivityData(_ data: DeviceActivityReport) -&gt; [AppUsageData] {<br>        var result: [AppUsageData] = []<br>        for activity in data.activitySegments {<br>            for app in activity.applicationActivity {<br>                let minutes = app.totalActivityDuration / 60<br>                result.append(AppUsageData(<br>                    appName: app.applicationName ?? app.bundleIdentifier,<br>                    usageTime: minutes,<br>                    category: activity.category ?? &quot;Other&quot;<br>                ))<br>            }<br>        }<br>        return result.sorted { $0.usageTime &gt; $1.usageTime }<br>    }<br>}<br><br>struct AppUsageData {<br>    let appName: String<br>    let usageTime: Double<br>    let category: String<br>    <br>    var formattedTime: String {<br>        let hours = Int(usageTime) / 60<br>        let minutes = Int(usageTime) % 60<br>        return hours &gt; 0 ? &quot;\(hours)h \(minutes)m&quot; : &quot;\(minutes)m&quot;<br>    }<br>}</pre><p>Let’s take it a step further to visualize app usage data .</p><p>— -</p><p><strong>## 📈 Building the Usage Pie Chart</strong></p><p>Here’s the UsagePieChartView to display app usage distribution:</p><pre>struct UsagePieChartView: View {<br>    let data: [AppUsageData]<br>    @Binding var selectedApp: String?<br>    <br>    private var totalUsage: Double {<br>        data.reduce(0) { $0 + $1.usageTime }<br>    }<br>    <br>    var body: some View {<br>        ZStack {<br>            ForEach(data.indices, id: \.self) { index in<br>                PieSliceView(<br>                    startAngle: startAngle(for: index),<br>                    endAngle: endAngle(for: index),<br>                    color: sliceColor(for: index),<br>                    isSelected: data[index].appName == selectedApp<br>                )<br>                .onTapGesture {<br>                    withAnimation(.easeInOut) {<br>                        selectedApp = selectedApp == data[index].appName ? nil : data[index].appName<br>                    }<br>                }<br>            }<br>            <br>            if let selected = selectedApp, let app = data.first(where: { $0.appName == selected }) {<br>                VStack {<br>                    Text(app.appName)<br>                        .font(.headline)<br>                    Text(app.formattedTime)<br>                        .font(.subheadline)<br>                    Text(&quot;\(Int((app.usageTime / totalUsage) * 100))%&quot;)<br>                        .font(.caption)<br>                }<br>            } else {<br>                let hours = Int(totalUsage) / 60<br>                let minutes = Int(totalUsage) % 60<br>                Text(&quot;Total: \(hours)h \(minutes)m&quot;)<br>                    .font(.headline)<br>            }<br>        }<br>    }<br>    <br>    private func startAngle(for index: Int) -&gt; Angle {<br>        let precedingTotal = data.prefix(index).reduce(0) { $0 + $1.usageTime }<br>        return .degrees((precedingTotal / totalUsage) * 360)<br>    }<br>    <br>    private func endAngle(for index: Int) -&gt; Angle {<br>        let precedingTotal = data.prefix(index + 1).reduce(0) { $0 + $1.usageTime }<br>        return .degrees((precedingTotal / totalUsage) * 360)<br>    }<br>    <br>    private func sliceColor(for index: Int) -&gt; Color {<br>        [.blue, .green, .orange, .red, .purple, .pink][index % 6]<br>    }<br>}<br><br>struct PieSliceView: View {<br>    let startAngle: Angle<br>    let endAngle: Angle<br>    let color: Color<br>    let isSelected: Bool<br>    <br>    var body: some View {<br>        GeometryReader { geometry in<br>            Path { path in<br>                let center = CGPoint(x: geometry.size.width / 2, y: geometry.size.height / 2)<br>                let radius = min(geometry.size.width, geometry.size.height) / 2<br>                path.move(to: center)<br>                path.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)<br>                path.closeSubpath()<br>            }<br>            .fill(color)<br>            .scaleEffect(isSelected ? 1.05 : 1.0)<br>            .shadow(radius: isSelected ? 5 : 0)<br>        }<br>    }<br>}</pre><p><strong>## Detailing App Usage with Rows</strong></p><p>The <strong>AppUsageRow</strong> provides a clean list entry:</p><pre>struct AppUsageRow: View {<br>    let app: AppUsageData<br>    let isSelected: Bool<br>    <br>    var body: some View {<br>        HStack {<br>            Circle()<br>                .fill(categoryColor(for: app.category))<br>                .frame(width: 12, height: 12)<br>            Text(app.appName)<br>                .font(.headline)<br>            Spacer()<br>            Text(app.formattedTime)<br>                .font(.subheadline)<br>                .foregroundColor(.secondary)<br>        }<br>        .padding(.vertical, 8)<br>        .background(isSelected ? Color.gray.opacity(0.2) : .clear)<br>        .cornerRadius(8)<br>    }<br>    <br>    private func categoryColor(for category: String) -&gt; Color {<br>        switch category.lowercased() {<br>        case &quot;social&quot;: return .blue<br>        case &quot;entertainment&quot;: return .red<br>        case &quot;productivity&quot;: return .green<br>        case &quot;games&quot;: return .orange<br>        default: return .gray<br>        }<br>    }<br>}</pre><p>— -</p><p><strong>### Building the Weekly Report View</strong></p><p>For a broader view, here’s the <strong>WeeklyReportView</strong> with a bar chart:</p><pre>struct WeeklyReportView: DeviceActivityReportScene {<br>    let context: DeviceActivityReport.Context<br>    <br>    @State private var weeklyData: [Date: [AppUsageData]] = [:]<br>    @State private var selectedDay: Date?<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;Weekly Activity Report&quot;)<br>                .font(.title2.bold())<br>            <br>            if weeklyData.isEmpty {<br>                ProgressView(&quot;Loading...&quot;)<br>            } else {<br>                WeeklyBarChartView(data: weeklyData, selectedDay: $selectedDay)<br>                    .frame(height: 200)<br>                <br>                if let day = selectedDay, let dayData = weeklyData[day] {<br>                    VStack(alignment: .leading) {<br>                        Text(day, style: .date)<br>                            .font(.headline)<br>                        List(dayData, id: \.appName) { app in<br>                            AppUsageRow(app: app, isSelected: false)<br>                        }<br>                        .listStyle(.plain)<br>                    }<br>                } else {<br>                    Text(&quot;Tap a day to see details&quot;)<br>                        .foregroundColor(.secondary)<br>                }<br>            }<br>        }<br>        .padding()<br>        .task { await loadWeeklyData() }<br>    }<br>    <br>    private func loadWeeklyData() async {<br>        let calendar = Calendar.current<br>        let endDate = context.intervalOfInterest.end<br>        <br>        do {<br>            let center = DeviceActivityCenter()<br>            for day in 0..&lt;7 {<br>                guard let start = calendar.date(byAdding: .day, value: -day, to: endDate),<br>                      let end = calendar.date(byAdding: .day, value: 1, to: start) else { continue }<br>                let interval = DateInterval(start: start, end: end)<br>                let data = try await center.activityReport(for: .init(intervalOfInterest: interval, categoryToken: &quot;daily&quot;))<br>                weeklyData[start] = processActivityData(data)<br>            }<br>            selectedDay = weeklyData.keys.max()<br>        } catch {<br>            print(&quot;Error loading weekly data: \(error)&quot;)<br>        }<br>    }<br>    <br>    private func processActivityData(_ data: DeviceActivityReport) -&gt; [AppUsageData] {<br>        // Same as DailyReportView<br>        var result: [AppUsageData] = []<br>        for activity in data.activitySegments {<br>            for app in activity.applicationActivity {<br>                let minutes = app.totalActivityDuration / 60<br>                result.append(AppUsageData(<br>                    appName: app.applicationName ?? app.bundleIdentifier,<br>                    usageTime: minutes,<br>                    category: activity.category ?? &quot;Other&quot;<br>                ))<br>            }<br>        }<br>        return result.sorted { $0.usageTime &gt; $1.usageTime }<br>    }<br>}<br><br>struct WeeklyBarChartView: View {<br>    let data: [Date: [AppUsageData]]<br>    @Binding var selectedDay: Date?<br>    <br>    private var sortedDays: [Date] { data.keys.sorted() }<br>    private func totalUsage(for day: Date) -&gt; Double { data[day]?.reduce(0) { $0 + $1.usageTime } ?? 0 }<br>    private var maxUsage: Double { sortedDays.map { totalUsage(for: $0) }.max() ?? 1 }<br>    <br>    var body: some View {<br>        HStack(alignment: .bottom, spacing: 10) {<br>            ForEach(sortedDays, id: \.self) { day in<br>                let usage = totalUsage(for: day)<br>                let height = (usage / maxUsage) * 150<br>                VStack {<br>                    Text(&quot;\(Int(usage / 60))h&quot;)<br>                        .font(.caption2)<br>                        .foregroundColor(.secondary)<br>                    Rectangle()<br>                        .fill(day == selectedDay ? .blue : .blue.opacity(0.6))<br>                        .frame(width: 30, height: max(CGFloat(height), 10))<br>                        .cornerRadius(4)<br>                    Text(day, format: .dateTime.weekday(.abbreviated))<br>                        .font(.caption2)<br>                        .foregroundColor(.secondary)<br>                }<br>                .onTapGesture {<br>                    withAnimation { selectedDay = day }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Storing Data Efficiently</h4><p>Here’s an improved ActivityDataManager using UserDefaults with an app group for sharing:</p><pre>class ActivityDataManager {<br>    static let shared = ActivityDataManager()<br>    private let userDefaults: UserDefaults?<br>    private let dataKey = &quot;StoredActivityData&quot;<br>    <br>    init() {<br>        userDefaults = UserDefaults(suiteName: &quot;group.com.yourapp.screentime&quot;)<br>    }<br>    <br>    func saveActivityData(_ data: [Date: [AppUsageData]], for date: Date) {<br>        guard let userDefaults else { return }<br>        var allData = userDefaults.dictionary(forKey: dataKey) as? [String: Any] ?? [:]<br>        let dateKey = ISO8601DateFormatter().string(from: date)<br>        allData[dateKey] = data.mapValues { $0.map { [&quot;name&quot;: $0.appName, &quot;time&quot;: $0.usageTime, &quot;category&quot;: $0.category] } }<br>        userDefaults.set(allData, forKey: dataKey)<br>    }<br>    <br>    func loadActivityData(for date: Date) -&gt; [Date: [AppUsageData]]? {<br>        guard let userDefaults,<br>              let allData = userDefaults.dictionary(forKey: dataKey) as? [String: Any],<br>              let dateData = allData[ISO8601DateFormatter().string(from: date)] as? [String: [[String: Any]]] else { return nil }<br>        <br>        return Dictionary(uniqueKeysWithValues: dateData.map { key, value in<br>            (ISO8601DateFormatter().date(from: key)!, value.compactMap {<br>                guard let name = $0[&quot;name&quot;] as? String, let time = $0[&quot;time&quot;] as? Double, let category = $0[&quot;category&quot;] as? String else { return nil }<br>                return AppUsageData(appName: name, usageTime: time, category: category)<br>            })<br>        })<br>    }<br>    <br>    func clearOldData(olderThan days: Int) {<br>        guard let userDefaults,<br>              var allData = userDefaults.dictionary(forKey: dataKey) as? [String: Any],<br>              let cutoff = Calendar.current.date(byAdding: .day, value: -days, to: Date()) else { return }<br>        let cutoffKey = ISO8601DateFormatter().string(from: cutoff)<br>        allData = allData.filter { $0.key &gt;= cutoffKey }<br>        userDefaults.set(allData, forKey: dataKey)<br>    }<br>}</pre><p><strong>Adding Insights and Recommendations</strong></p><p>Here’s an enhanced InsightsView:</p><pre>struct InsightsView: View {<br>    let weeklyData: [Date: [AppUsageData]]<br>    <br>    @State private var mostUsedApp = &quot;&quot;<br>    @State private var avgDailyUsage: Double = 0<br>    @State private var trend: Trend = .stable<br>    <br>    enum Trend { case increasing, decreasing, stable }<br>    <br>    var body: some View {<br>        VStack(alignment: .leading, spacing: 20) {<br>            Text(&quot;Your Screen Time Insights&quot;)<br>                .font(.title2.bold())<br>            <br>            InsightCard(title: &quot;Most Used App&quot;, value: mostUsedApp, icon: &quot;app.badge&quot;, color: .blue)<br>            InsightCard(title: &quot;Avg. Daily Usage&quot;, value: formatTime(avgDailyUsage), icon: &quot;clock&quot;, color: .green)<br>            InsightCard(title: &quot;Weekly Trend&quot;, value: trend.rawValue.capitalized, icon: trendIcon, color: trendColor)<br>            <br>            recommendationView<br>        }<br>        .padding()<br>        .task { calculateInsights() }<br>    }<br>    <br>    private var trendIcon: String {<br>        switch trend {<br>        case .increasing: return &quot;arrow.up.right&quot;<br>        case .decreasing: return &quot;arrow.down.right&quot;<br>        case .stable: return &quot;equal&quot;<br>        }<br>    }<br>    <br>    private var trendColor: Color {<br>        switch trend {<br>        case .increasing: return .red<br>        case .decreasing: return .green<br>        case .stable: return .blue<br>        }<br>    }<br>    <br>    private var recommendationView: some View {<br>        VStack(alignment: .leading, spacing: 10) {<br>            Text(&quot;Recommendations&quot;)<br>                .font(.headline)<br>            Text(recommendationText)<br>                .font(.subheadline)<br>        }<br>        .padding()<br>        .background(Color.gray.opacity(0.1))<br>        .cornerRadius(12)<br>    }<br>    <br>    private var recommendationText: String {<br>        if trend == .increasing { return &quot;Your screen time is rising. Try limiting \(mostUsedApp).&quot; }<br>        else if avgDailyUsage &gt; 180 { return &quot;Over 3h daily—schedule some breaks!&quot; }<br>        else { return &quot;Great job maintaining healthy habits!&quot; }<br>    }<br>    <br>    private func calculateInsights() {<br>        guard !weeklyData.isEmpty else { return }<br>        <br>        // Most used app<br>        var appTotals: [String: Double] = [:]<br>        weeklyData.values.forEach { $0.forEach { appTotals[$0.appName, default: 0] += $0.usageTime } }<br>        mostUsedApp = appTotals.max(by: { $0.value &lt; $1.value })?.key ?? &quot;None&quot;<br>        <br>        // Average daily usage<br>        let totalUsage = weeklyData.values.reduce(0) { $0 + $1.reduce(0) { $0 + $1.usageTime } }<br>        avgDailyUsage = totalUsage / Double(weeklyData.count)<br>        <br>        // Trend<br>        let sortedDays = weeklyData.keys.sorted()<br>        if sortedDays.count &gt;= 3 {<br>            let recent = sortedDays.suffix(3).map { weeklyData[$0]?.reduce(0) { $0 + $1.usageTime } ?? 0 }<br>            if recent[2] &gt; recent[0] * 1.2 { trend = .increasing }<br>            else if recent[0] &gt; recent[2] * 1.2 { trend = .decreasing }<br>            else { trend = .stable }<br>        }<br>    }<br>    <br>    private func formatTime(_ minutes: Double) -&gt; String {<br>        let hours = Int(minutes) / 60<br>        let mins = Int(minutes) % 60<br>        return hours &gt; 0 ? &quot;\(hours)h \(mins)m&quot; : &quot;\(mins)m&quot;<br>    }<br>}<br><br>struct InsightCard: View {<br>    let title: String<br>    let value: String<br>    let icon: String<br>    let color: Color<br>    <br>    var body: some View {<br>        HStack(spacing: 12) {<br>            Image(systemName: icon)<br>                .foregroundColor(color)<br>                .frame(width: 30)<br>            VStack(alignment: .leading) {<br>                Text(title)<br>                    .font(.subheadline)<br>                    .foregroundColor(.secondary)<br>                Text(value)<br>                    .font(.headline)<br>            }<br>            Spacer()<br>        }<br>        .padding()<br>        .background(Color.gray.opacity(0.1))<br>        .cornerRadius(12)<br>    }<br>}</pre><h4>Integrating into Your App</h4><p>Display the report in your main app:</p><pre>struct ScreenTimeReportView: View {<br>    @State private var reportType = &quot;daily&quot;<br>    <br>    var body: some View {<br>        VStack {<br>            Picker(&quot;Report Type&quot;, selection: $reportType) {<br>                Text(&quot;Daily&quot;).tag(&quot;daily&quot;)<br>                Text(&quot;Weekly&quot;).tag(&quot;weekly&quot;)<br>            }<br>            .pickerStyle(.segmented)<br>            .padding()<br>            <br>            if let start = intervalStart {<br>                DeviceActivityReport(.init(<br>                    intervalOfInterest: DateInterval(start: start, end: .now),<br>                    categoryToken: reportType<br>                ))<br>                .frame(maxHeight: 400)<br>            } else {<br>                Text(&quot;Error calculating interval&quot;)<br>                    .foregroundColor(.secondary)<br>            }<br>        }<br>        .navigationTitle(&quot;Screen Time&quot;)<br>    }<br>    <br>    private var intervalStart: Date? {<br>        let calendar = Calendar.current<br>        switch reportType {<br>        case &quot;daily&quot;: return calendar.startOfDay(for: .now)<br>        case &quot;weekly&quot;: return calendar.date(byAdding: .day, value: -6, to: calendar.startOfDay(for: .now))<br>        default: return nil<br>        }<br>    }<br>}</pre><p>Using the Device Activity Report extension, you’ve transformed raw Screen Time data into a meaningful narrative — from daily breakdowns with pie charts to weekly trends with bar charts, all paired with insights that promote healthier usage. Your app is now more than a tool; it’s a trusted guide for digital wellness.</p><p><strong>Resources</strong></p><ul><li><a href="https://developer.apple.com/documentation/deviceactivity/deviceactivityreportextension">Device Activity Report Extension Docs</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2022/110339/">WWDC22: Screen Time API</a></li><li><a href="https://developer.apple.com/design/human-interface-guidelines/technologies/screen-time">Human Interface Guidelines: Screen Time</a></li></ul><p><strong>🚀 Wrapping Up</strong></p><p>Well done! You’ve successfully implemented a powerful approach to visualize screen time data with the Device Activity Report Extension. 📚</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a761a8daed55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Apple’s Screen Time API (Part 3): Implementing Shields and Custom Shields]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-apples-screen-time-api-part-3-implementing-shields-and-custom-shields-792eec4a2174?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/792eec4a2174</guid>
            <category><![CDATA[parental-control-app]]></category>
            <category><![CDATA[screentime]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[apple-screen-time]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 05:13:47 GMT</pubDate>
            <atom:updated>2025-03-13T05:13:47.824Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous parts, we discussed setting up the Screen Time API, requesting authorization, and implementing Device Activity Monitoring. Now, let’s move forward to implementing **Shields** and customizing their behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1crjXa5lFlj_uyu095G4zA.png" /></figure><p><strong>🔐 What are Shields?</strong></p><p>Shields are an essential feature of Apple’s Screen Time API that allows developers to **restrict access to specific apps or categories** by displaying a blocking interface. This is highly useful for parental control apps and productivity tools where limiting access is necessary.</p><p><strong>Common Use Cases:</strong><br>- Blocking social media apps during focus hours.<br>- Creating time-limited app usage sessions.<br>- Restricting access to specific apps for child accounts.</p><p>— -</p><p><strong>📲 Setting Up Shields</strong></p><p>The code to update app restrictions using Shields is straightforward. You can **activate and deactivate shields** using the `ManagedSettingsStore` API.</p><p>✅ <strong>Applying Shields</strong></p><p>Here’s how to apply shields to selected apps:</p><pre><br>import ManagedSettings<br>func updateRestrictions(for selectedApps: FamilyActivitySelection) {<br> let store = ManagedSettingsStore()<br> <br> // Apply shields to selected applications<br> if store.shield.applications == nil {<br> store.shield.applications = selectedApps.applicationTokens<br> }<br>}</pre><p>In the above code:<br>- `ManagedSettingsStore`: Provides access to the current shield settings.<br>- `store.shield.applications`: Specifies the list of apps to be restricted by their tokens.</p><p>✅ <strong>Removing Shields (Unblocking Apps)</strong></p><p>If you want to remove shields and restore access to the previously blocked apps, use the following code:</p><pre><br>func unblockApps() {<br> let store = ManagedSettingsStore()<br> <br> // Clear all app restrictions<br> store.shield.applications = nil<br> print(“All restrictions have been cleared.”)<br>}</pre><p>This code effectively clears all restrictions applied through `store.shield`.</p><p>📲 <strong>Creating Custom Shield UI</strong></p><p>To customize the shield UI, you need to create a **Shield Extension**. This allows you to provide a tailored interface when a user attempts to open a blocked app.</p><p>✅ <strong>Adding a Shield Extension</strong><br>1. In Xcode, select your project from the Project Navigator.<br>2. Click the “+” button under the **Targets** section.<br>3. Choose `Shield Extension` and click **Next**.<br>4. Give your extension a unique name (e.g., `CustomShieldExtension`) and click **Finish**.<br>5. Enable **Family Controls Capability** under **Signing &amp; Capabilities**.</p><p>🔨 <strong>Implementing `ShieldConfigurationExtension`</strong></p><p>When you create a Shield Extension, a default file called `ShieldConfigurationExtension.swift` is generated. This file allows you to customize how the shield behaves.</p><p>Example:</p><pre>import ManagedSettings<br><br>class ShieldConfigurationExtension: ShieldConfigurationDataSource {<br>    override func configuration(shielding application: Application) -&gt; ShieldConfiguration {<br>        let appName = application.localizedDisplayName ?? &quot;&quot; // Fetching the blocked app name<br>        <br>        return ShieldConfiguration(<br>            backgroundBlurStyle: .dark,<br>            backgroundColor: .black,<br>            icon: UIImage(named: &quot;applogo.png&quot;),<br>            title: ShieldConfiguration.Label(<br>                text: &quot;\(appName) is Restricted&quot;,<br>                color: .white<br>            ),<br>            subtitle: ShieldConfiguration.Label(<br>                text: &quot;You have reached your time limit for this app.&quot;,<br>                color: .white<br>            ),<br>            primaryButtonLabel: ShieldConfiguration.Label(<br>                text: &quot;Close&quot;,<br>                color: .black<br>            ),<br>            primaryButtonBackgroundColor: .white,<br>            secondaryButtonLabel: nil<br>        )<br>    }<br>}</pre><p>📌 <strong>Where to Customize Shield UI</strong><br>- The above code is part of your **Shield Extension**, specifically in the `ShieldConfigurationExtension.swift` file.<br>- This customization happens in your **extension target** and not the main app target.<br>- You can modify the UI by adjusting parameters such as `backgroundBlurStyle`, `backgroundColor`, `icon`, `title`, and `subtitle`.</p><p><strong>📖 Summary</strong></p><p>In this part, we’ve covered how to implement and customize Shields using the `ManagedSettingsStore` API. Additionally, we’ve shown how to create a **Custom Shield Extension** to personalize the blocking interface.</p><p>In the next part, we’ll focus on how to visualize and manage activity data effectively. Stay tuned!</p><p>If you found this guide helpful, make sure to check out the next part! Also, feel free to leave a comment if you have any questions or suggestions. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=792eec4a2174" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Apple’s Screen Time API (Part 2): Implementing Device Activity Monitoring]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-apples-screen-time-api-part-2-implementing-device-activity-monitoring-ef395029f8f2?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef395029f8f2</guid>
            <category><![CDATA[apple-patent-application]]></category>
            <category><![CDATA[screentime]]></category>
            <category><![CDATA[apple-screen-time]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 05:22:32 GMT</pubDate>
            <atom:updated>2025-03-12T05:46:46.197Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous part, we covered the basics of getting started with the Screen Time API and requesting authorization. Now, it’s time to dive into **Device Activity Monitoring**, which allows us to track app usage over specific intervals via a separate extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1crjXa5lFlj_uyu095G4zA.png" /></figure><p>📌 <strong>What is Device Activity Monitoring?</strong><br>The **Device Activity Monitoring** feature enables developers to monitor and analyze device usage patterns. With this tool, you can collect data on which apps are being used, how long they’re being used, and set up triggers for enforcing restrictions.</p><p><strong>Common Use Cases:</strong><br>- Tracking daily and weekly app usage.<br>- Setting daily limits for specific apps.<br>- Monitoring activity patterns for productivity or parental control purposes.</p><p>🔐 <strong>Setting Up Device Activity Monitor as a Separate Target</strong><br>To properly implement `DeviceActivityMonitor`, you need to add a new target to your Xcode project. Follow these steps:</p><p>✅ <strong>Adding Device Activity Monitor Extension</strong><br>1. <strong>Create a New Target:</strong><br> — In Xcode, select your project from the Project Navigator.<br> — Click the “+” button under the **Targets** section.<br> — Choose `Device Activity Monitor Extension` and click **Next**.<br> — Give your extension a unique name (e.g., `ActivityMonitorExtension`) and click **Finish**.</p><p>2. <strong>Enable Family Controls Capability:</strong><br> — Go to your extension’s target settings.<br> — Navigate to **Signing &amp; Capabilities**.<br> — Click the “+ Capability” button and add **Family Controls**.</p><p>📲<strong> Implementing the Monitoring Code in the Extension</strong></p><p>📌 <strong>Understanding Threshold</strong><br>The `threshold` defines the maximum allowed usage time before the `eventDidReachThreshold()` method is triggered. It is specified in seconds as a `TimeInterval`.</p><p>For example, to set a daily usage limit of **1 hour**, the threshold would be:</p><pre>let threshold: TimeInterval = 3600 // 1 hour in seconds</pre><p>You can adjust this value as needed to implement different time limits.</p><p>📌 <strong>Where to Use `FamilyActivityPicker`</strong><br>The `FamilyActivityPicker` should be used in your **main app**, not the extension. This is because the picker UI is meant for user interaction, which isn’t possible within an extension. Once the user selects the apps to monitor, their tokens can be stored and passed to your extension for monitoring purposes.</p><p>To start monitoring, we need to pass the apps selected by the user. Here’s how to obtain the selected apps:</p><pre>import FamilyControls<br><br> @State private var selectedApps = FamilyActivitySelection()<br><br>.familyActivityPicker(isPresented: $isPresented, selection: $selectedApps)</pre><p>The `selectedApps()` function uses the **FamilyActivityPicker** to allow the user to choose which apps they want to monitor.</p><p>In your main app (not the extension), add the following code to start monitoring:</p><pre>import DeviceActivity<br>import FamilyControls<br><br>let activityMonitor = DeviceActivityMonitor()<br><br>func startMonitoring(selectedApps: FamilyActivitySelection, threshold: TimeInterval) {<br>    let event = DeviceActivityEvent(<br>        applications: selectedApps.applicationTokens,<br>        threshold: threshold<br>    )<br><br>    let events: [DeviceActivityEvent.Name: DeviceActivityEvent] = [<br>        .init(&quot;daily_limit&quot;): event<br>    ]<br><br>    let allDaySchedule = DeviceActivitySchedule(<br>        intervalStart: DateComponents(hour: 0, minute: 0),<br>        intervalEnd: DateComponents(hour: 23, minute: 59),<br>        repeats: true<br>    )<br><br>    do {<br>        try activityMonitor.startMonitoring(<br>            .init(rawValue: &quot;com.yourapp.activity&quot;),<br>            during: allDaySchedule,<br>            events: events<br>        )<br>        print(&quot;Device activity monitoring started successfully.&quot;)<br>    } catch {<br>        print(&quot;Error starting monitoring: \(error)&quot;)<br>    }<br>}</pre><p>📌 <strong>Explanation of Code</strong><br>- <em>DeviceActivityEvent</em>: Defines the applications to monitor with a specified time threshold.<br>- <em>DeviceActivityEvent.Name</em>: A unique name to identify the event. (Avoid using `time_limit` as per your request.)<br>- <em>DeviceActivitySchedule</em>: Defines the monitoring interval and whether it repeats daily.<br>- <em>activityMonitor.startMonitoring()</em>: Starts the monitoring process.</p><p>📌 <strong>Handling Monitoring Events</strong><br>You need to implement methods to respond when intervals start, end, or when activities are detected. Here are the main methods:</p><pre>func intervalDidStart(for activity: DeviceActivityName) {<br> print(&quot;Monitoring interval started for: \(activity.rawValue)&quot;)<br>}<br>func intervalDidEnd(for activity: DeviceActivityName) {<br> print(&quot;Monitoring interval ended for: \(activity.rawValue)&quot;)<br>}<br>func eventDidReachThreshold(_ event: DeviceActivityEvent.Name, for activity: DeviceActivityName) {<br> print(&quot;Threshold reached for event: \(event.rawValue)&quot;)<br>}</pre><p>📌 <strong>Explanation of Methods</strong><br>- `intervalDidStart()`: Called when the monitoring interval begins.<br>- `intervalDidEnd()`: Called when the monitoring interval ends.<br>- `eventDidReachThreshold()`: Called when the event threshold is reached (e.g., daily limit exceeded).</p><p>📌 <strong>Stopping Monitoring</strong><br>To stop monitoring from your extension:</p><pre>func stopMonitoring() {<br> activityMonitor.stopMonitoring()<br> print(&quot;Device activity monitoring stopped.&quot;)<br>}</pre><p>📖 <strong>Summary</strong><br>In this part, we’ve covered how to set up a **Device Activity Monitor Extension** as a separate target and start monitoring device activity with detailed code explanations. In the next part, we’ll explore how to visualize this data with **Device Activity Graphs**.</p><p>If you found this guide helpful, make sure to check out the next part! Also, feel free to leave a comment if you have any questions or suggestions. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef395029f8f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Apple’s Screen Time API (Part 1): Getting Started with Apple’s Screen Time API]]></title>
            <link>https://medium.com/@manishdevstudio/mastering-apples-screen-time-api-part-1-getting-started-with-apple-s-screen-time-api-926436cf94f9?source=rss-2cb23729549c------2</link>
            <guid isPermaLink="false">https://medium.com/p/926436cf94f9</guid>
            <category><![CDATA[apple-screen-time]]></category>
            <category><![CDATA[apple-patent-application]]></category>
            <dc:creator><![CDATA[Manish Yadav]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 04:35:26 GMT</pubDate>
            <atom:updated>2025-03-12T04:43:05.747Z</atom:updated>
            <content:encoded><![CDATA[<p>Apple’s Screen Time API provides developers with the ability to monitor and control app usage on iOS devices. This powerful tool is particularly useful for building parental control apps, productivity tools, and apps focused on promoting digital well-being.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1crjXa5lFlj_uyu095G4zA.png" /></figure><p><strong>📌</strong> <strong>What is the Screen Time API?</strong><br>Apple’s Screen Time API is designed to allow developers to track and restrict application usage on a device. It’s commonly used for:<br>- Monitoring daily and weekly usage of apps.<br>- Creating app restrictions and shields to enforce limits.<br>- Providing insights into device activity through visual representations.</p><p>💡 <strong>Use Cases</strong><br>- **Parental Control Apps:** Limiting children’s screen time and ensuring they use devices responsibly.<br>- **Productivity Apps:** Encouraging focused work sessions by blocking distracting apps.<br>- **Health &amp; Wellness Apps:** Promoting balanced device usage to improve digital well-being.</p><p>🔐 <strong>Permissions Required</strong><br>To use the Screen Time API, your app needs permission to access device activity data and enforce restrictions. You’ll need to:<br>- **Request authorization from the user.**<br>- **Enable Family Controls capability** in your Xcode project.</p><p>✅ <strong>Enabling Permissions in Xcode</strong><br>1. Open your Xcode project.<br>2. Select your app’s target and navigate to **Signing &amp; Capabilities**.<br>3. Click the “+ Capability” button and add **Family Controls**.</p><p>You should now see **Family Controls** listed under your app’s capabilities.</p><p>📲 <strong>Setting Up the Screen Time API in SwiftUI</strong><br>Start by importing the required frameworks:</p><pre>import DeviceActivity<br>import ManagedSettings<br>import FamilyControls</pre><p><strong>Requesting Authorization</strong><br>Before you can monitor activity or enforce restrictions, you need to request authorization from the user:</p><pre>import FamilyControls<br><br>struct ContentView: View {<br>    @State private var authorizationStatus = AuthorizationCenter.shared.status<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Screen Time API Example&quot;)<br>            <br>            Button(&quot;Request Authorization&quot;) {<br>                AuthorizationCenter.shared.requestAuthorization { status, error in<br>                    if let error = error {<br>                        print(&quot;Error requesting authorization: \(error.localizedDescription)&quot;)<br>                    } else {<br>                        authorizationStatus = status<br>                        print(&quot;Authorization status: \(status.rawValue)&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br></pre><p>🔍 <strong>Checking Authorization Status</strong><br>It’s important to check the user’s authorization status to ensure your app can proceed:</p><pre>func checkAuthorizationStatus() {<br>    let status = AuthorizationCenter.shared.status<br>    if status == .approved {<br>        print(&quot;Authorization granted&quot;)<br>    } else {<br>        print(&quot;Authorization not granted&quot;)<br>    }<br>}</pre><p>This basic setup ensures your app is ready to interact with the Screen Time API. In the next part, we’ll dive into how to effectively monitor device activity using `DeviceActivityMonitor`.</p><p>If you enjoyed this article and found it helpful, stay tuned for Part 2! I’ll be covering **Device Activity Monitoring** in detail. Feel free to leave your comments and share your thoughts. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926436cf94f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>