惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
WordPress大学
WordPress大学
S
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
AWS News Blog
AWS News Blog
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
NISL@THU
NISL@THU
T
Tor Project blog
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 聂微东
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
G
GRAHAM CLULEY
博客园_首页
K
Kaspersky official blog
GbyAI
GbyAI
P
Privacy & Cybersecurity Law Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
AI
AI
爱范儿
爱范儿
Cloudbric
Cloudbric
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
aimingoo的专栏
aimingoo的专栏
I
InfoQ
腾讯CDC
O
OpenAI News
F
Full Disclosure
P
Privacy International News Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Webroot Blog
Webroot Blog
Forbes - Security
Forbes - Security
MyScale Blog
MyScale Blog
L
LangChain Blog
H
Help Net Security
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
人人都是产品经理
人人都是产品经理
S
Security @ Cisco Blogs
T
Tenable Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
News and Events Feed by Topic
博客园 - 三生石上(FineUI控件)
Attack and Defense Labs
Attack and Defense Labs
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
WWDC 2026 - Build Real-Time Apps and Services with gRPC and Swift
ArshTechPro · 2026-06-22 · via DEV Community

If you have ever hand-written networking code to talk to a backend, you know the pain. You read some documentation, design your request and response types, write the URL handling and JSON decoding, and eventually get something that seems to work. Then the API changes, the docs fall behind, a field gets renamed, and suddenly your app is silently failing in production.

gRPC removes most of that friction. Instead of treating server communication as a pile of HTTP endpoints and hand-rolled models, gRPC lets you define your API once, in a single contract, and generate the client and server code from it. With the release of gRPC Swift 2, this workflow has become genuinely idiomatic on Apple platforms and Linux, built around async/await and Swift 6 concurrency.

This article walks through what gRPC is, why it fits real-time apps so well, and how to use it in a Swift project from start to finish.

What is gRPC?

gRPC is a framework for making remote procedure calls.

The key mental shift is this: with a typical REST API, you think in terms of HTTP, like URLs, verbs such as GET and POST, status codes, and request bodies. With gRPC, you think in terms of functions with inputs and outputs. Calling the server feels like calling a local function, except the work happens on a remote machine.

A remote procedure call works like this:

  1. The client builds a request message.
  2. It sends that message to the server.
  3. The server runs the function and produces a response message.
  4. The response travels back to the client.

For example, a function to fetch a race schedule might be called listRaces. The client calls it with the number of races it wants, and the server returns the list. From the caller's perspective, it looks almost identical to invoking any other Swift method.

gRPC is not a niche tool. It runs deep inside large-scale infrastructure, including Apple's own services such as Private Cloud Compute, iCloud Keychain, Photos, and SharePlay file sharing, as well as inter-process communication in Apple's open source Containerization framework. The same library you would use in an iOS app is production-grade for backend systems.

The contract: Protocol Buffers

Most gRPC services describe their API using Protocol Buffers, usually shortened to Protobuf. This is the source of truth for the service. Because it is a neutral, cross-platform format, the same .proto file can generate a Swift client, a Go server, a Kotlin client, and so on. Everyone agrees on the same contract.

You define your service and its messages in a .proto file. Here is a small example for a racing app:

syntax = "proto3";

import "google/protobuf/timestamp.proto";

service SwiftKart {
  rpc ListRaces(ListRacesRequest) returns (ListRacesResponse);
}

message ListRacesRequest {
  int32 limit = 1;
}

message ListRacesResponse {
  repeated Race races = 1;
}

message Race {
  string name = 1;
  string location = 2;
  string championship = 3;
  int32 laps = 4;
  google.protobuf.Timestamp start_time = 5;
}

A few things worth noticing:

  • The service block declares one or more RPCs. Here, ListRaces takes a ListRacesRequest and returns a ListRacesResponse.
  • Every field has a unique field number (the = 1, = 2, and so on). These numbers, not the names, are what gets sent on the wire.
  • repeated means a list, so repeated Race races is the equivalent of an array of races.
  • Timestamp is one of Protobuf's "Well-Known Types," which is why it needs an import.

Why the field numbers matter

When gRPC sends a message, it serializes it to a compact binary representation and uses the field number rather than the field name to identify each value. The practical result is that a Protobuf message is roughly half the size of the equivalent JSON payload.

For a mobile app, smaller messages mean less data transferred and faster network calls, which matters most when the connection is poor. The same efficiency pays off in service-to-service communication on the backend.

Setting up gRPC Swift in your project

gRPC Swift 2 is distributed as a set of packages so you can pull in only what you need. The three you will most commonly use are:

  • grpc-swift-2 provides the core runtime types and abstractions (GRPCCore).
  • grpc-swift-nio-transport provides high-performance HTTP/2 networking built on SwiftNIO.
  • grpc-swift-protobuf provides the build plugin that generates Swift code from your .proto files, and integrates with SwiftProtobuf.

In a Swift package, your dependencies look like this:

// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "SwiftKart",
    platforms: [.macOS("15.0"), .iOS("18.0")],
    dependencies: [
        .package(url: "https://github.com/grpc/grpc-swift-2.git", from: "2.0.0"),
        .package(url: "https://github.com/grpc/grpc-swift-nio-transport.git", from: "2.0.0"),
        .package(url: "https://github.com/grpc/grpc-swift-protobuf.git", from: "2.0.0"),
    ],
    targets: [
        .executableTarget(
            name: "SwiftKart",
            dependencies: [
                .product(name: "GRPCCore", package: "grpc-swift-2"),
                .product(name: "GRPCNIOTransportHTTP2", package: "grpc-swift-nio-transport"),
                .product(name: "GRPCProtobuf", package: "grpc-swift-protobuf"),
            ],
            plugins: [
                .plugin(name: "GRPCProtobufGenerator", package: "grpc-swift-protobuf")
            ]
        )
    ]
)

Note: gRPC Swift 2 requires Swift 6 and recent deployment targets (macOS 15+, iOS 18+, tvOS 18+, watchOS 11+, visionOS 2+).

Generating the code in Xcode

If you are working in an Xcode app project rather than a pure Swift package, the flow is:

  1. Open the Project Editor, go to the Package Dependencies tab, and add grpc-swift-nio-transport and grpc-swift-protobuf.
  2. Select your app target, open Build Phases, and expand Run Build Tool Plug-ins.
  3. Add the GRPCProtobufGenerator plugin.
  4. Drop your .proto file and a small JSON config file into the target.

The plugin scans the target for .proto files and generates the Swift code when you build. The JSON config controls what gets generated. For an app, you typically only need the messages and the client, not the server code:

{
  "generate": {
    "clients": true,
    "messages": true,
    "servers": false
  }
}

The first time you build, Xcode will ask you to trust the plugin. After that, your generated client and message types are available to import.

Making your first call

With the code generated, calling the service from a SwiftUI view looks like ordinary async Swift. Here is the shape of it:

import GRPCCore
import GRPCNIOTransportHTTP2
import SwiftProtobuf

// Inside a view, using a .task modifier:
.task {
    do {
        try await withGRPCClient(
            transport: .http2NIOPosix(
                target: .dns(host: "localhost", port: 8080),
                transportSecurity: .plaintext
            )
        ) { client in
            let kart = SwiftKart.Client(wrapping: client)
            let response = try await kart.listRaces(.with { $0.limit = 50 })
            self.races = response.races.map(Race.init)
        }
    } catch {
        print("Request failed: \(error)")
    }
}

What is happening here:

  • withGRPCClient creates a client configured with a transport. The transport decides how the bytes move, in this case HTTP/2 over SwiftNIO, connecting to a local server.
  • The raw client only knows about the server, not your specific service. Wrapping it in the generated SwiftKart.Client gives you the typed listRaces method.
  • .with { $0.limit = 50 } is the SwiftProtobuf way of building a message and setting its fields.
  • The response is mapped into the app's own model types.

And that is a complete round trip: a typed request out, a typed response back, with no manual URL building or JSON decoding anywhere.

Reuse the client, do not recreate it

One important detail: do not create a new gRPC client every time a view appears. Each client establishes its own connection, which adds latency. Instead, create a single client and share it, for example through the SwiftUI environment, so connections can be reused across views.

It is also good practice to disconnect the client when the app moves to the background to free up resources. A small "client manager" object that connects lazily and tears down on scenePhase changes handles this cleanly.

The real power: streaming

So far we have looked at a unary RPC, which is a single request and a single response, just like a normal function call. This is where gRPC's standout feature comes in: every RPC can also stream messages. That opens up three more call types beyond unary.

RPC type Client sends Server sends Good for
Unary one message one message Fetching a list, a single lookup
Server streaming one message many messages Live commentary feed, notifications
Client streaming many messages one message Uploading telemetry, batching events
Bidirectional streaming many messages many messages Live, two-way subscriptions

Think about a live kart race:

  • Server streaming is a live text commentary feed. The client asks once, the server keeps pushing updates.
  • Client streaming is each kart pushing its telemetry to the server continuously.
  • Bidirectional streaming is the richest case. The client tells the server which events it cares about and can change that subscription at any time, while the server streams back the matching events.

Defining a streaming RPC

You mark a streaming parameter with the stream keyword in the .proto file:

service SwiftKart {
  rpc ListRaces(ListRacesRequest) returns (ListRacesResponse);

  rpc FollowRace(stream FollowRaceRequest) returns (stream FollowRaceResponse);
}

message FollowRaceRequest {
  string race_name = 1;
  repeated EventType events = 2;
}

enum EventType {
  EVENT_TYPE_UNSPECIFIED = 0;
  EVENT_TYPE_KART_LOCATIONS = 1;
  EVENT_TYPE_STANDINGS = 2;
}

message FollowRaceResponse {
  oneof payload {
    KartLocations locations = 1;
    Standings standings = 2;
  }
}

That oneof is worth calling out: it maps neatly onto a Swift enum with associated values. A FollowRaceResponse holds either kart locations or standings, and you switch over it on the client just like any Swift enum.

Consuming a bidirectional stream on the client

A bidirectional RPC gives you two closures: one for writing requests to the server, and one for reading responses. Here is the shape of consuming the live race feed in SwiftUI:

.task {
    do {
        try await manager.withClient { client in
            let kart = SwiftKart.Client(wrapping: client)

            try await kart.followRace { writer in
                // Send a request whenever the user's interests change.
                for await showLeaderboard in leaderboardStream {
                    var request = FollowRaceRequest.with {
                        $0.raceName = "Finite Loops"
                        $0.events = [.kartLocations]
                    }
                    if showLeaderboard {
                        request.events.append(.standings)
                    }
                    try await writer.write(request)
                }
            } onResponse: { responses in
                // Handle each event the server pushes back.
                for try await response in responses.messages {
                    handle(response)
                }
            }
        }
    } catch {
        print("Stream failed: \(error)")
    }
}

The two halves run concurrently. As the user toggles the leaderboard on and off, the client writes new request messages updating its subscription, and the server adjusts what it streams back in real time. The handle(response) helper switches over the oneof payload and updates the view, drawing kart positions on a map or refreshing the standings.

This is the core of a real-time experience: a single long-lived connection carrying a live, two-way conversation, with strongly typed messages on both ends.

Implementing the server side

The same .proto contract generates the server code too. Implementing a service means conforming to a generated protocol, with one method per RPC. For a unary RPC, that is just an async function:

import GRPCCore
import GRPCNIOTransportHTTP2

struct SwiftKartService: SwiftKart.SimpleServiceProtocol {
    func listRaces(
        request: ListRacesRequest,
        context: ServerContext
    ) async throws -> ListRacesResponse {
        let races = try await database.races(limit: Int(request.limit))
        return ListRacesResponse.with { $0.races = races }
    }
}

Starting the server is a matter of creating one with a transport and the services it should offer, then calling serve():

let server = GRPCServer(
    transport: .http2NIOPosix(
        address: .ipv4(host: "0.0.0.0", port: 8080),
        transportSecurity: .plaintext
    ),
    services: [SwiftKartService()]
)
try await server.serve()

Streaming RPCs on the server look a little different. The request parameter becomes an async sequence of incoming messages, and the response becomes a writer you push messages into. Handling two streams at once is a natural fit for a Swift task group: one task reads the client's evolving subscription, another follows the live race data and writes matching events back. When the request stream ends, you treat that as the signal to cancel the work and stop sending.

Deploying to the cloud

Because gRPC Swift runs on Linux, deploying a service is the standard container workflow. Most cloud providers (Google Cloud Run, AWS, Fly.io, and others) follow a similar pattern even if the exact commands differ.

The typical steps:

  1. Write a Containerfile that builds the server in release mode. Use a multi-stage build: compile with the full swift:latest image, then copy just the resulting binary into a smaller swift:slim runtime image. This keeps the final image from carrying the entire Swift toolchain.
  2. Publish the image to your provider's container registry.
  3. Create a deployment. Make sure to enable HTTP/2, since gRPC depends on it.
  4. Update the app to point at the deployed service's DNS name, and switch the transport security from plaintext to TLS.

That last change on the client is small but essential:

.http2NIOPosix(
    target: .dns(host: "your-service.example.run.app", port: 443),
    transportSecurity: .tls   // was .plaintext for local development
)

With TLS enabled and the host pointed at the cloud, the same app that talked to your Mac now talks to a service available to everyone.

Where to go next

gRPC Swift has plenty built in to take an app from prototype to production:

  • Integration with other Swift server packages like Swift OTel (for distributed tracing via OpenTelemetry) and Swift Service Lifecycle.
  • Advanced connection management, including custom transports, name resolvers, and client-side load balancing.
  • A reflection service, health checks, and interceptors via the grpc-swift-extras package.

The fastest way to get comfortable is to prototype one slice of your app-to-server communication with gRPC and feel how the generated code removes the boilerplate. From there:

  • Browse the tutorials and examples in the grpc-swift-2 repository.

  • Since the project is open source, you can ask questions, improve docs, or propose features.