<?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 Matheus Veras Batista on Medium]]></title>
        <description><![CDATA[Stories by Matheus Veras Batista on Medium]]></description>
        <link>https://medium.com/@matheus.vbatista04?source=rss-3176902dc65d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yOdRZIVYYMxRnD6a</url>
            <title>Stories by Matheus Veras Batista on Medium</title>
            <link>https://medium.com/@matheus.vbatista04?source=rss-3176902dc65d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matheus.vbatista04/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[Triggering remote push notifications via APNs with Go, Rust and Node]]></title>
            <link>https://medium.com/@matheus.vbatista04/triggering-remote-push-notifications-via-apns-with-go-rust-and-node-bfea9e561137?source=rss-3176902dc65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfea9e561137</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[notification-service]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Matheus Veras Batista]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 23:00:13 GMT</pubDate>
            <atom:updated>2023-10-23T23:00:13.306Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sending remote push notifications for Apple devices is pretty straightforward, and can be done in simple steps.</h4><p>Sample projects source code:<br>- Go: <a href="https://github.com/matheus-vb/APNs-go">https://github.com/matheus-vb/APNs-go</a><br>- Rust: <a href="https://github.com/matheus-vb/APNs-rust">https://github.com/matheus-vb/APNs-rust</a><br>- Node: <a href="https://github.com/matheus-vb/APNs-node">https://github.com/matheus-vb/APNs-node</a></p><p>Recently, I developed a feature for a macOS app that included sending push notifications remotely to devices. The technology used then in the project&#39;s backend then was Node and Typescript, so I used the &#39;node-apn&#39; package to access Apple&#39;s notification API. Since I was also studying web development using Rust and Go at the time, I took the chance to develop sample projects for testing out the notification API sandbox using these languages.</p><p>The general approach for using the APN service consists of setting up the provider — using private key or certificate — and then using the provider to push a notification.</p><p>What is needed to make use of the APNs is a private key or certificate (how to obtain either one <a href="https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server#">here</a>), and allowing the app (iOS, macOS, iPadOS, etc) to use the push notification service using a delegate (checkout how to register the service in an app <a href="https://developer.apple.com/documentation/usernotifications/registering_your_app_with_apns">here</a>). For the examples developed here, I am going to use a private key, obtained in the form of a .p8 file, downloaded in Apple Developer&#39;s platform.</p><p>To test out the service with more flexibility, I chose to trigger notifications using a http endpoint in a server. When the endpoint /trigger/(device_token) is hit (where device_token is the device&#39;s token obtained when the user accepts to receive notifications), a notification is pushed to the device.</p><p>The private key must be placed on the root of the project, alongside a .env file in the following format:</p><pre>KEY_ID=your-key-id<br>TEAM_ID=your-team-id<br>BUNDLE_ID=the-app&#39;s-bundle-id</pre><p>The KEY_ID and TEAM_ID should come from your the Apple Developer platform, while the BUNDLE_ID is your app&#39;s Bundle ID.</p><h3>Node</h3><p>To implement the service with Node, the <a href="https://github.com/node-apn/node-apn">node-apn</a> package was used. Here is the setup for the provider:</p><pre>import apn from &quot;apn&quot;;<br>import { env } from &quot;./env&quot;;<br><br>let options: apn.ProviderOptions = {<br>    token: {<br>        key: &quot;./auth-key.p8&quot;,<br>        keyId: env.KEY_ID,<br>        teamId: env.TEAM_ID,<br>    },<br>    production: false<br>}<br><br>export const apnProvider = new apn.Provider(options);</pre><p>Here, the provider is setup using the environment variables and the path to the private key file.</p><p>Here is how the provider can be used to push a notification:</p><pre>import apn from &quot;apn&quot;;<br>import { env } from &quot;./env&quot;;<br><br>export function sendNotification(deviceToken: string, provider: apn.Provider) {<br>    var notification = new apn.Notification();<br><br>    notification.topic = env.BUNDLE_ID<br>    notification.expiry = Math.floor(Date.now() / 1000) + 3600;<br>    notification.badge = 3;<br>    notification.sound = &quot;default&quot;;<br>    notification.alert = &quot;Message from Node!&quot;;<br>    notification.payload = {&#39;messageFrom&#39;: &#39;Node.js&#39;};<br><br>    provider.send(notification, deviceToken).then((result) =&gt; {<br>        console.log(result.failed)<br>        console.log(result.sent)<br>    })<br>}</pre><p>The function can then be tested out in a simple server, like mentioned before:</p><pre>import fastify from &quot;fastify&quot;;<br>import { apnProvider } from &quot;./apn&quot;;<br>import { env } from &quot;./env&quot;;<br>import { sendNotification } from &quot;./send-notification&quot;;<br>import { z } from &quot;zod&quot;;<br><br>const app = fastify();<br>const provider = apnProvider;<br><br>app.get(&#39;/trigger/:deviceToken&#39;, async (request, reply) =&gt; {<br>    const triggerSchema = z.object({<br>        deviceToken: z.string(),<br>    })<br><br>    const { deviceToken } = triggerSchema.parse(request.params);<br><br>    sendNotification(deviceToken, provider);<br><br>    return reply.status(200).send({ data: &quot;APNs called.&quot; })<br>})<br><br>app.listen({<br>    host: &quot;0.0.0.0&quot;,<br>    port: env.PORT,<br>}).then(() =&gt; {<br>    console.log(`Server running on port ${env.PORT}.`)<br>})</pre><h3>Go</h3><p>To test out the APNs using Go, the <a href="https://github.com/sideshow/apns2">sideshow/apns2</a> package was used. Here is how the provider was setup:</p><pre>package internal<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/sideshow/apns2&quot;<br> &quot;github.com/sideshow/apns2/token&quot;<br> &quot;log&quot;<br>)<br><br>type Provider struct {<br> KeyId   string<br> TeamId  string<br> KeyFile string<br> Topic   string<br> Client  *apns2.Client<br>}<br><br>func (provider *Provider) SetupProvider() *Provider {<br> authKey, err := token.AuthKeyFromFile(provider.KeyFile)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> log.Println(&quot;Key loaded&quot;)<br><br> newToken := &amp;token.Token{<br>  AuthKey: authKey,<br>  KeyID:   provider.KeyId,<br>  TeamID:  provider.TeamId,<br> }<br><br> provider.Client = apns2.NewTokenClient(newToken).Development()<br><br> log.Println(&quot;Provider client setup done&quot;)<br><br> return provider<br>}<br><br>func (provider *Provider) SendNotification(deviceToken string, message string) (*apns2.Response, error) {<br> notification := &amp;apns2.Notification{<br>  DeviceToken: deviceToken,<br>  Topic:       provider.Topic,<br>  Payload:     []byte(fmt.Sprintf(`{&quot;aps&quot;:{&quot;alert&quot;:&quot;%s&quot;}}`, message)),<br> }<br><br> res, err := provider.Client.Push(notification)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> return res, nil<br>}</pre><p>The handler for triggering the notification service:</p><pre>package api<br><br>import (<br> &quot;github.com/go-chi/chi/v5&quot;<br> &quot;go-server/util&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)<br><br>func (app *App) SendNotification(w http.ResponseWriter, r *http.Request) {<br> deviceToken := chi.URLParam(r, &quot;deviceToken&quot;)<br><br> res, err := app.Provider.SendNotification(deviceToken, &quot;Message from Go!&quot;)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> payload := util.JSONResponse{<br>  Error:   false,<br>  Message: &quot;APNs call result&quot;,<br>  Data:    res.Sent(),<br> }<br><br> err = util.WriteJSON(w, http.StatusOK, payload)<br> if err != nil {<br>  log.Println(err)<br> }<br>}</pre><h3>Rust</h3><p>The Rust code follows the same steps, using the <a href="https://github.com/WalletConnect/a2">WalletConnect/a2</a> package. The first step is setting up the provider, and then pushing the notification once the endpoint is hit. Here is the setup code:</p><pre>pub fn setup_client() -&gt; Result&lt;Client, Box&lt;dyn Error&gt;&gt; {<br>    const KEY_FILE: &amp;str = &quot;auth-key.p8&quot;; // path to .p8 key file<br><br>    let key_id = env::var(&quot;KEY_ID&quot;).expect(&quot;KEY_ID must be set&quot;);<br>    let team_id = env::var(&quot;TEAM_ID&quot;).expect(&quot;TEAM_ID must be set&quot;);<br>    <br>    let endpoint = Endpoint::Sandbox; // APNs environment <br><br>    let private_key = match File::open(KEY_FILE) {<br>        Ok(file) =&gt; file,<br>        Err(e) =&gt; {<br>            error!(&quot;Failed to open key file: {}&quot;, e);<br>            return Err(e.into())<br>        }<br>    };<br><br>    info!(&quot;Key file: {:?}&quot;, private_key);<br>    info!(&quot;Key id: {}&quot;, key_id);<br>    info!(&quot;Team id: {}&quot;, team_id);<br><br>    match Client::token(private_key, &amp;key_id, &amp;team_id, endpoint) {<br>        Ok(client) =&gt; Ok(client),<br>        Err(e) =&gt; {<br>            error!(&quot;Failed to create client: {}&quot;, e);<br>            Err(e.into())<br>        }<br>    }<br>}</pre><p>Using the client to push notifications:</p><pre>pub async fn send_notification(<br>    client: &amp;Client,<br>    device_token: &amp;str<br>) -&gt; Result&lt;(), Box&lt;dyn std::error::Error + Send + Sync&gt;&gt; {<br>    let topic = Some(env::var(&quot;BUNDLE_ID&quot;).expect(&quot;BUNDLE_ID must be set&quot;));<br><br>    let options = NotificationOptions {<br>        apns_topic: topic.as_deref(),<br>        ..Default::default()<br>    };<br>    <br>    let message = &quot;Message from Rust!&quot;; // Notification message<br><br>    // Notification payload<br>    let builder = DefaultNotificationBuilder::new()<br>        .set_body(message.as_ref())<br>        .set_sound(&quot;default&quot;)<br>        .set_badge(1u32);<br><br>    let payload = builder.build(device_token.as_ref(), options);<br>    <br>    match client.send(payload).await {<br>        Ok(response) =&gt; {<br>            info!(&quot;Sent: {:?}&quot;, response);<br>            Ok(())<br>        }<br>        Err(e) =&gt; {<br>            error!(&quot;Failed to send notification: {}&quot;, e);<br>            Err(e.into())<br>        }<br>    }<br>}</pre><p>And here&#39;s how the notification service was exposed to a server&#39;s endpoint:</p><pre>#[derive(Serialize)]<br>struct ApiResponse {<br>    data: String,<br>}<br><br>#[get(&quot;/trigger/{device_token}&quot;)]<br>pub async fn trigger(<br>    client: Data&lt;Arc&lt;Client&gt;&gt;,<br>    device_token: web::Path&lt;String&gt;<br>) -&gt; impl Responder {<br>    match send_notification(client.get_ref(), device_token.as_str()).await {<br>        Ok(_) =&gt; HttpResponse::Ok().json(ApiResponse { data: &quot;Notification sent.&quot;.to_string() }),<br>        Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>    }<br>}</pre><p>Overall, making usage of Apple&#39;s Push Notification Service is pretty simple, regardless of the technology used. To further information on how the APNs works, and how to make the most of it in a production environment, checkout <a href="https://developer.apple.com/documentation/usernotifications">Apple&#39;s documentation on User Notifications</a>.</p><p>The source code for the sample projects:<br>- Go: <a href="https://github.com/matheus-vb/APNs-go">https://github.com/matheus-vb/APNs-go</a><br>- Rust: <a href="https://github.com/matheus-vb/APNs-rust">https://github.com/matheus-vb/APNs-rust</a><br>- Node: <a href="https://github.com/matheus-vb/APNs-node">https://github.com/matheus-vb/APNs-node</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfea9e561137" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pulling user data from Apple Music API using Swift]]></title>
            <link>https://medium.com/@matheus.vbatista04/pulling-user-data-from-apple-music-api-using-swift-20f1ce5e353a?source=rss-3176902dc65d------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f1ce5e353a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[apple-music]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Matheus Veras Batista]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 02:45:25 GMT</pubDate>
            <atom:updated>2022-09-30T02:45:25.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4xTj23enl0BHxUxHudkrg.jpeg" /></figure><p>In 2017, Apple announced, during the WWDC, the release of MusicKit, a framework designed to allow developers to obtain and use information from Apple Music with ease, using the Apple Music API, alongside other frameworks.</p><p>In this story, I&#39;ll explain how to use the Apple Music API to retrieve information using Swift. First of all, to make use of the API, you are going to need to get the developer token. To do that, follow the <strong>Create a MusicKit Identifier,</strong> and then the<strong> Create a Private Key</strong> sections in <a href="https://www.appcoda.com/musickit-music-player-swiftui/">this article</a>.</p><p>Once the token is in hands, you can start to make use of the API in your app. To do such, we are going to create a new .swift file, and inside it, a class named AppleMusicAPI, where the functions and variables used are going to be written.</p><blockquote><em>Note: the developer token is being put here to make it easier to visualize, but you should put it somewhere it won&#39;t be shared without your permission. If you put your app in a public repository, make sure the token is in a file listed in the .gitignore.</em></blockquote><pre>import StoreKit</pre><pre>class AppleMusicAPI {<br>    let developerToken = &quot;YOURTOKEN&quot;</pre><pre>}   </pre><p>If the data you seek to gather is user related, such as the user&#39;s recently listened tracks, or favorite albums and playlists, you are going to need to use StoreKit to get the user&#39;s token.</p><h3>Obtaining the User&#39;s token</h3><p>The first step to gather the user&#39;s token is to go to the Info.plist file in your project. In the Information Property List section, tap the + button, and then select &quot;Privacy — Media Library Usage Description&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*oaWzRrbfgUaD84Myebd9Zw.png" /></figure><p>In your code, the fuction below is the first that is going to be written, and it will return a string with the user&#39;s token. This token will be used further in the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfea90a9d7bd8dc5ac3536bfba28de00/href">https://medium.com/media/dfea90a9d7bd8dc5ac3536bfba28de00/href</a></iframe><h3>Building the requisition</h3><p>Now that we can get the the token from the user, we can start building the functions with the actual requisitions from the API. To find out all the kinds of data you can grab with the API, check out the documentation <a href="https://developer.apple.com/documentation/applemusicapi/">here</a>. In this exemple, I&#39;m going to ask for the users recently listened tracks, with the following request:</p><pre>https://api.music.apple.com/v1/me/recent/played/tracks</pre><p>In order to use and manipulate the data that is going to be pulled, we&#39;re going to need to convert the JSON into objects, built according to each response orientation. Each type of response has different attributes, and they can all be checked out in the <a href="https://developer.apple.com/documentation/applemusicapi/">API&#39;s documentation</a>. Here is an exemple of the song type response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9f62e8702ad0c1240f8dd79e55c8dc/href">https://medium.com/media/5b9f62e8702ad0c1240f8dd79e55c8dc/href</a></iframe><p>For this exemple, only the song&#39;s ID, name and artist are going to be relevant. Therefore, here is our Song type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60d3b498027c027c626c2ab187d16df1/href">https://medium.com/media/60d3b498027c027c626c2ab187d16df1/href</a></iframe><p>Since the requisition is going to return an array of songs, it will be necessary to create a type containing an array of the type Song</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3610674d06ddf1cd0ecd86054e46b9d2/href">https://medium.com/media/3610674d06ddf1cd0ecd86054e46b9d2/href</a></iframe><p>Now that it&#39;s all set, we can pull information from the API and decode it into an array of objects. The fetchSongs function below is the one responsible for that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03612abeb5402e360c385affa175aea2/href">https://medium.com/media/03612abeb5402e360c385affa175aea2/href</a></iframe><h3>Making actual use of the API</h3><p>The fucntion above is going to return an array containing the songs the users has listened to recently. Now, to make use of what we just wrote, we are going to create a View Controller that fetches the data once is loaded, and prints in the terminal the name and artist of each one of the songs collected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b720108c7f0396b108b569140eea5cbe/href">https://medium.com/media/b720108c7f0396b108b569140eea5cbe/href</a></iframe><p>Here, you have everything you need to grab all kinds of data that the API makes available. For different requisitions, make sure to check out the <a href="https://developer.apple.com/">documentation</a>. Remember that, for different types of responses, you&#39;re going to need to build different types of objects to be decoded in to.</p><p>With the information in your app, you can now do as you please. Good luck, and I hope the content here helped somehow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f1ce5e353a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>