<?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 Andrey Gordeev on Medium]]></title>
        <description><![CDATA[Stories by Andrey Gordeev on Medium]]></description>
        <link>https://medium.com/@agordeev?source=rss-5946a4eff410------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fwe2jQkTWzr-AskfZe3GEA.jpeg</url>
            <title>Stories by Andrey Gordeev on Medium</title>
            <link>https://medium.com/@agordeev?source=rss-5946a4eff410------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:48:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agordeev/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[An Unfortunate Mistake We Made In Our Garden]]></title>
            <link>https://agordeev.medium.com/an-unfortunate-mistake-we-made-in-our-garden-cda98454d2ba?source=rss-5946a4eff410------2</link>
            <guid isPermaLink="false">https://medium.com/p/cda98454d2ba</guid>
            <category><![CDATA[home-decor]]></category>
            <category><![CDATA[garden]]></category>
            <category><![CDATA[plants]]></category>
            <category><![CDATA[vegetables]]></category>
            <category><![CDATA[gardening]]></category>
            <dc:creator><![CDATA[Andrey Gordeev]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 05:39:02 GMT</pubDate>
            <atom:updated>2020-11-18T09:08:31.093Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Mobile App That Prevents Annoying Mistakes in Our Garden</h3><p>Such stories happen to each of us. Our family owns a garden where we grow various vegetables and fruits. In 2018 we started growing carrots in our garden. It was a very good variety of large, sweet, bright orange carrots. We were very happy with the big harvest.</p><figure><img alt="Carrots" src="https://cdn-images-1.medium.com/max/1024/1*FMaON79lEehNHXvxssFf4A.jpeg" /></figure><p>Next spring we decided to plant this variety again. We tried to remember the name of this variety, but with no luck. The bag was thrown away, and the purchase history was not preserved. We were desperate… Choosing the right variety is not easy, since our soil is not very good. Because of this, in 2019, choosing a carrot variety was again like a lottery.</p><p>This problem could be easily avoided if we had written down the name of the variety we liked in a safe place. To solve this problem (and many others) we created Leafarise: a mobile app for gardeners. Among other functions, Leafarise allows us to keep a garden journal in a convenient form. Now, when buying seeds, we make an entry about this in our garden journal and attach a photo.</p><figure><img alt="Adding a garden diary entry in Leafarise mobile app for gardeners" src="https://cdn-images-1.medium.com/max/1024/1*37_Qj9NvD-mndMqpQGMB8g.png" /><figcaption>A journal entry can be linked with our carrot bed</figcaption></figure><p>Carrots do not need fertilization, but it is helpful to write this down for other plants such as tomatoes and fruit trees. We also record how much was harvested in order to compare varieties with each other and choose the best.</p><figure><img alt="The journal screen in Leafarise mobile app for gardeners" src="https://cdn-images-1.medium.com/max/1024/1*PwL-vWKP9ZP7ky-0eWgGPA.png" /><figcaption>This is how our garden journal looks like</figcaption></figure><p>Keeping garden notes in Leafarise is easy, fast and convenient. My phone is always in the pocket, even when I’m in the garden. I can take a photo or check info about my plants at any time. It is impossible to lose data, even if I have lost my phone, because all data is safely stored on the server.</p><p>Get early access to Leafarise now if you’re interested. All early adopters get <strong>free lifetime access</strong> to the app. Here are instructions:</p><ul><li><a href="https://testflight.apple.com/join/KofNmQd6">iOS</a></li><li><a href="https://play.google.com/store/apps/details?id=com.leafarise.leafarise">Android</a></li></ul><p>Join our <a href="https://www.facebook.com/groups/leafarisebeta">Facebook group</a> for discussion.</p><p>Learn more:</p><ul><li><a href="https://agordeev.medium.com/leafarise-a-mobile-app-for-gardeners-456a59b2eb9c">Leafarise: A Mobile App for Gardeners</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cda98454d2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leafarise: a mobile app for gardeners]]></title>
            <link>https://agordeev.medium.com/leafarise-a-mobile-app-for-gardeners-456a59b2eb9c?source=rss-5946a4eff410------2</link>
            <guid isPermaLink="false">https://medium.com/p/456a59b2eb9c</guid>
            <category><![CDATA[gardening]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[home-improvement]]></category>
            <category><![CDATA[growing-up]]></category>
            <category><![CDATA[vegetable-garden]]></category>
            <dc:creator><![CDATA[Andrey Gordeev]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 06:11:23 GMT</pubDate>
            <atom:updated>2020-11-18T05:50:48.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leafarise: a Mobile App for Gardeners</h3><p>Gardening is not easy. To facilitate the gardening experience we have created Leafarise.</p><p>Leafarise is a mobile app that helps to be a better gardener. With Leafarise you can organize your garden, track its performance and keep the garden diary.</p><h3>Plants</h3><figure><img alt="The plants screen of Leafarise mobile app for gardeners" src="https://cdn-images-1.medium.com/max/1024/1*T2CAueVhWW1h0OYPweJkdA.png" /><figcaption>All plants in your garden are displayed here</figcaption></figure><p>The plants screen shows all the plants the gardener has in his garden. This includes flowers, vegetables, shrubs and trees. It is also helpful to indicate the plant variety. For example: Rosa ‘Bonica’ or Cucumber ‘La Diva’.</p><h3>Plantings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkWvKJtJt0r7gfJVIzDALw.png" /><figcaption>A row of tomatoes on the planting screen</figcaption></figure><p>This is where all garden beds are located. This includes flowers, vegetables, shrubs and trees. The user can select the soil type, sunlight exposure and planting date.</p><p>A planting can be of two types: a multiple planting and a single planting. It’s very easy to distinguish between them. A multiple planting can consist of many plants. Consider, for example, a flower bed, a carrot bed, or a row of apricot trees. On the other hand, a single planting is one plant planted. For example, an apple tree, or a family oak.</p><figure><img alt="Adding an apple tree in Leafarise mobile app for gardeners" src="https://cdn-images-1.medium.com/max/1024/1*kxZmTxtztDUUB3voM-3RQQ.png" /><figcaption>Adding an apple tree</figcaption></figure><p>This will give you a complete list of plants and plantings in your garden. Awesome!</p><h3>Calendar</h3><figure><img alt="The calendar screen of Leafarise mobile app for gardeners" src="https://cdn-images-1.medium.com/max/1024/1*hTR31vyw_s0cdXFGJMTUPQ.png" /><figcaption>With Leafarise you can manage your garden tasks</figcaption></figure><p>Tasks are useful for planning garden related works. They can also be linked with a planting, just like notes. For example, a gardener can create a “<strong>Harvest tomatoes”</strong> task and link it with the tomatoes bed he previously created on the plantings screen. In this case, the task will automatically appear in the “Calendar” window of this plant. Convenient and familiar calendar view makes it easy to navigate through the months.</p><p>The tasks you add are also displayed on the journal screen.</p><h3>Journal</h3><figure><img alt="The journal screen of Leafarise mobile app for gardeners" src="https://cdn-images-1.medium.com/max/1024/1*7-1ln0zgGAvpTsEOf_K9Ig.png" /><figcaption>The garden diary</figcaption></figure><p>The journal screen is useful for keeping all your garden related notes and tasks. The gardener can write what was done in the garden today, or describe some observations made. Garden notes can be linked to a planting on the plantings screen. Here’s how keeping a garden diary helps with the garden improvement:</p><ul><li><strong>Learn from your success and mistakes</strong>. How much fertilizer does this plant need? When should perennials be divided? You will never forget this anymore.</li><li><strong>Avoid extra expenses</strong> on plants you don’t like. If a plant isn’t good enough for your garden, write a note about it in the garden journal to avoid unnecessary purchases in the future.</li><li><strong>A better pest control.</strong> We’re facing with pests annually. Looking at the previous experience it’s easIer to pick the right time to fight pests.</li><li><strong>Turn ideas into a plan</strong>. Don’t miss ideas: add them to your garden journal so you don’t forget them.</li></ul><p>Using a mobile app for this comes with even greater benefits:</p><ul><li><strong>Never lose your garden journal.</strong> It is kept safe and available to you from any device.</li><li><strong>Access everywhere</strong>. It’s always in your pocket, even when you’re gardening.</li></ul><h3>Future plans</h3><p>Our mission is to create the best app for gardeners around the world. We have a long roadmap with interesting features for you. Here are some of them:</p><ul><li>Visual garden layout editor.</li><li>Family access.</li><li>Task reminders.</li><li>AI for analyzing and improving your gardening behavior.</li><li>…and many more!</li></ul><p>Leafarise is a good fit for any gardener. Get early access now, free of charge:</p><ul><li><a href="https://testflight.apple.com/join/KofNmQd6">iOS</a></li><li><a href="https://play.google.com/store/apps/details?id=com.leafarise.leafarise">Android</a></li></ul><p>Join our <a href="https://www.facebook.com/groups/leafarisebeta">Facebook group</a> for discussion.</p><p>Learn more:</p><ul><li><a href="https://agordeev.medium.com/an-unfortunate-mistake-we-made-in-our-garden-cda98454d2ba">How Leafarise helps to prevent annoying mistakes in our garden</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=456a59b2eb9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing iOS Social Network App Architecture]]></title>
            <link>https://agordeev.medium.com/designing-ios-social-network-app-architecture-d6bf76a94ce4?source=rss-5946a4eff410------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6bf76a94ce4</guid>
            <category><![CDATA[parse]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Andrey Gordeev]]></dc:creator>
            <pubDate>Mon, 14 Nov 2016 16:16:30 GMT</pubDate>
            <atom:updated>2016-11-14T16:16:30.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zvJMuFjoXyRG9HCmwXYoHQ.jpeg" /></figure><p>Recently I’ve released iOS social network app template called <a href="https://sociumapp.com/">Socium</a>. Here I’d like to share with you my knowledge learned from developing it.</p><h3>List of features</h3><p>First of all, we need to write down a list of features we want to see in the app. For example Socium, just as a typical social network app, has the following features:</p><ul><li>User profiles</li><li>User posts and comments</li><li>Post likes</li><li>Browsing and searching other users</li><li>Private realtime chats</li><li>Followings/followers</li><li>Push notifications</li></ul><p>Having this list in mind we can select a backend for the project.</p><h3>Backend</h3><p>Social network application is a complex system, consisting of client side and server side. Socium’s server side is built on top of <a href="http://parseplatform.github.io/">Parse Server</a>. There are many advantages of Parse Server: it’s open sourced, has a large community and has a great iOS SDK (as well as Android SDK, by the way). Parse Server requires a VPS or a cloud application platform like Heroku, which could be hard to setup and maintain for those, who are not familiar with backend stuff. However, I believe having control over the backend is a good thing. Even if it requires some additional skills. After all, <a href="https://www.reddit.com/r/iOSProgramming/comments/43gf6n/discussion_should_a_lesson_have_been_learned_from/">I learn from lessons</a>.</p><h3>Database schema</h3><p>Now when we know the requirements it’s time to write down all necessary tables and relationships between them. Here’s the schema I’ve designed for Socium:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*GIL0PYQHITqPS21L1UhR7g.png" /><figcaption>Socium database schema</figcaption></figure><p>Let’s run through few most interesting entities (or “classes” in Parse Server terminology).</p><p><strong>User</strong>/<strong>UserProfile</strong>. To protect the user’s email I‘ve created another class for public user profile called <strong>UserProfile</strong> and add one-to-one relationship with <strong>User</strong> class. <strong>UserProfile</strong> is visible to anyone. <strong>User</strong> is visible only to the owner and the admin.</p><p><strong>UserProfile</strong> has <em>followings</em>, <em>followers</em> and <em>postLikes</em> fields, which are one-to-many relationships to <strong>UserProfile</strong> and <strong>Post</strong> entity respectively. All of them</p><p><strong>Image</strong>. Instead of storing images directly in <strong>PFFile</strong> field I’ve created a separate class for that. Therefore images can be stored in array and many-to-many relationships. This gives a better flexibility if we’ll want to add, for example, like/unlike functionality to a photo.</p><p><strong>Post</strong>, <strong>PostComment</strong>, <strong>Conversation</strong> and <strong>Message</strong> entities are pretty self-explanatory.</p><h3>The client app architecture</h3><p>After we’ve defined the database schema it’s time to think about our iOS app. The app must:</p><ul><li>Display the content fast and efficiently.</li><li>Interact with the user.</li><li>Send requests to the server and receive responses from the server.</li><li>Be testable and maintainable.</li></ul><p>A standard Apple’s MVC design pattern won’t be a best fit for such quite big project. <a href="https://www.objc.io/issues/13-architecture/viper/">VIPER</a> looks much better. However, VIPER has pretty high barriers to entry. Since Socium is the iOS app template created for wide range of developers (and even non-developers), it could be uneasy to understand the project for someone.</p><p>Finally, I’ve decided to mix MVC approach with service-oriented architecture: all the business logic is stored in <em>Services</em>, which are separated from <em>ViewControllers</em>. Thus, a view controller never interacts with the backend directly. Instead, it asks an appropriate service to do something it needs. Services interact with the backend, work with models and handle CRUD (create, read, update, delete) operations. Each model (<strong>Post</strong>, <strong>UserProfile</strong>, <strong>Message</strong>) has an appropriate service (<strong>PostService</strong>, <strong>UserProfileService</strong>, <strong>MessageService</strong>).</p><p>It’s worth noting that models are not subclasses of <em>PFObject</em>, as in future we may want to hook up another backend (not Parse Server). That’s why services aslo need to parse objects to our models and vice versa. To keep a <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility principle</a> I’ve separated the parsing logic into <em>Parsers.</em></p><p>Here’s how the architecture looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*8CiiVG-29nfDJyIP0cEMUQ.png" /></figure><p>Note the app stores the retrieved objects in a cache. Each service has it’s own cache. Initially, I was thinking to store the objects in a plain array right in a service. However, it’s useful if a cache has such methods like <em>appendEntityIfNeeded, appendEntitiesIfNeeded, removeEntity</em> etc. All of them could (and should) be separated into another class, which acts as a cache. I didn’t set a requirement to implement the data persistence, so no Core Data used. The cache flushes as soon as the app shuts down.</p><p>It is also very useful to separate the UI part into a modules. Each module would have it’s own storyboard and a set of view controllers. Services can’t always be attributed to any particular module, so I prefer to place them into a special <em>Shared</em> folder. Other common classes, helpers, utilities also goes into <em>Shared</em>. Here’s more detailed schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*7Q4cO09KkeEEgEE4EnFZgg.png" /></figure><p>That’s it! As you can see, we’ve got simple yet solid, expandable and testable architecture for the social network app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6bf76a94ce4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get Parse Background Job functionality on Parse Server]]></title>
            <link>https://agordeev.medium.com/how-to-get-parse-background-job-functionality-on-parse-server-6bb86f210d09?source=rss-5946a4eff410------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb86f210d09</guid>
            <category><![CDATA[parse]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrey Gordeev]]></dc:creator>
            <pubDate>Thu, 04 Aug 2016 07:17:30 GMT</pubDate>
            <atom:updated>2016-11-21T15:18:11.658Z</atom:updated>
            <content:encoded><![CDATA[<p>One of important features missing in Parse Server is background scheduled job functionality. In <a href="https://github.com/ParsePlatform/parse-server/wiki/Compatibility-with-Hosted-Parse">this doc</a> Parse Team recommends us to use <a href="https://github.com/Automattic/kue">kue</a> for this purpose. Well, let’s check it out!</p><p><strong>kue </strong>is open source Node.js module, developed for managing a priority job queue. However, it doesn’t allow to schedule jobs out of the box, so we’ll need another utility called <strong>kue-scheduler</strong> for this. Both of them are easy to install and use.</p><p><strong>Prerequisites: kue</strong> is backed by <a href="http://redis.io/">Redis,</a> so we’d need to set Redis up before we start integrating <strong>kue</strong>. DigitalOcean has a great tutorial how to install and configure Redis on your server: <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis">https://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis</a>. Please follow it until <em>Redis Operations</em> part, then come back here.</p><p>After you’ve installed Redis, run this command to install <strong>kue</strong> and <strong>kue-scheduler</strong> globally:</p><pre>sudo npm install -g kue kue-scheduler</pre><p>Now we’re able to adapt our CloudCode for Parse Server. Let’s say you had a background job for posting a POST request to a webhook every hour. Here’s how it would look like on good ol’ Parse.com:</p><pre>Parse.Cloud.job(&quot;sendReport&quot;, function(request, response) {<br>  Parse.Cloud.httpRequest({<br>  method: &#39;POST&#39;,<br>  headers: {<br>   &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  },<br>  url: &quot;<a href="https://example.com/url/">https://example.com/url/</a>&quot;, // Webhook url<br>  body: &quot;body goes here&quot;,<br>  success: function(httpResponse) {<br>      console.log(&quot;Successfully POSTed to the webhook&quot;);<br>      },<br>  error: function(httpResponse) {<br>      console.error(&quot;Couldn&#39;t POST to webhook: &quot; + httpResponse);<br>      }<br>  });<br>});</pre><p>However, Parse Server doesn’t have <em>Parse.Cloud.job </em>function, so it will throw the following error:</p><pre>TypeError: Parse.Cloud.job is not a function</pre><p>To fix the error, replace that part by this code:</p><pre>// Create a kue instance and a queue.<br>var kue = require(&#39;kue-scheduler&#39;);<br>var Queue = kue.createQueue();<br>var jobName = &quot;sendReport&quot;;</pre><pre>// Clear all previous jobs.<br>Queue.clear(function(error, response) {<br>    // Create a job instance in the queue.<br>    var job = Queue<br>                .createJob(jobName)<br>                // Priority can be &#39;low&#39;, &#39;normal&#39;, &#39;medium&#39;, &#39;high&#39; and &#39;critical&#39;<br>                .priority(&#39;normal&#39;)<br>                // We don&#39;t want to keep the job in memory after it&#39;s completed.<br>                .removeOnComplete(true);<br>    <br>    // Schedule it to run every 60 minutes. Function every(interval, job) accepts interval in either a human-interval String format or a cron String format.<br>    Queue.every(&#39;60 minutes&#39;, job);<br>    <br>    // Processing a scheduled job.<br>    Queue.process(jobName, sendReport);<br>});</pre><pre>// The body of job goes here.<br>function sendReport(job, done) { <br>  Parse.Cloud.httpRequest({<br>  method: &#39;POST&#39;,<br>  headers: {<br>   &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  },<br>  url: &quot;<a href="https://example.com/url/">https://example.com/url/</a>&quot;, // Webhook url<br>  body: &quot;body goes here&quot;}).then(function(httpResponse) {<br>    console.log(&quot;Successfully POSTed to the webhook&quot;);<br>    // Don&#39;t forget to run done() when job is done.<br>    done();<br>  }, function(httpResponse) {<br>    var errorMessage = &quot;Couldn&#39;t POST to webhook: &quot; + httpResponse;<br>    console.error(errorMessage);<br>    // Pass Error object to done() to mark this job as failed.<br>    done(new Error(errorMessage));<br>  });<br>}</pre><p>That’s it! This Cloud Code would run just fine on Parse Server. This is a pretty basic example of what<strong> kue </strong>can do, so I strongly recommend you to check out it’s <a href="https://github.com/Automattic/kue">documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bb86f210d09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning with Sprite Kit]]></title>
            <link>https://agordeev.medium.com/lightning-with-sprite-kit-9aba4963698d?source=rss-5946a4eff410------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aba4963698d</guid>
            <category><![CDATA[spritekit]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Andrey Gordeev]]></dc:creator>
            <pubDate>Sun, 14 Feb 2016 07:07:18 GMT</pubDate>
            <atom:updated>2016-02-14T07:07:18.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Jb1PVNmVU7FIO-9K2Nf-ew.gif" /></figure><p>Have you ever tried to implement such effect as lightning for your iOS game? In this article I’m going to describe <strong>three ways</strong> I found to create a lightning effect with a decent quality:</p><ul><li>SKShapeNode.</li><li>CAShapeLayer.</li><li>SKSpriteNodes.</li></ul><p>For each of them we need to compose a path for our lightning bolt. I searched the web and found <a href="http://krazydad.com/bestiary/bestiary_lightning.html">this article</a> about procedural generation of lightning bolt. This approach uses <strong>Midpoint Displacement</strong> algorithm. The result looks pretty realistic. Here is Objective-C code for Midpoint Displacement algorithm:</p><pre>void createBolt(float x1, float y1, float x2, float y2, float displace, UIBezierPath *path) {<br>    if (displace &lt; 1.8f) {<br>        CGPoint point = CGPointMake(x2, y2);<br>        [path MoveToPoint:point];<br>    }<br>    else {<br>        float mid_x = (x2+x1)*0.5f;<br>        float mid_y = (y2+y1)*0.5f;<br>        mid_x += (arc4random_uniform(100)*0.01f-0.5f)*displace;<br>        mid_y += (arc4random_uniform(100)*0.01f-0.5f)*displace;<br>        createBolt(x1, y1, mid_x, mid_y, displace*0.5f, path);<br>        createBolt(mid_x, mid_y, x2, y2, displace*0.5f, path);<br>    }<br>}</pre><p>Ok, we got the path, how about drawing it? “We can define <strong>SKShapeNode</strong> with our path!” — that’s how I thought.</p><h3>SKShapeNode.</h3><p>Let’s create <strong>SKShapeNode</strong> with <strong>UIBezierPath</strong>, created from our <em>pathArray</em>:</p><pre>- (void)addBoltWithStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {<br>    // Dynamically calculating displace<br>    // Distance between two points<br>    float hypot = hypotf(fabsf(endPoint.x - startPoint.x), fabsf(endPoint.y - startPoint.y));<br>    // hypot/displace = 4/1<br>    float displace = hypot*0.25;<br> <br>    UIBezierPath *path = [UIBezierPath bezierPath];<br>    [path moveToPoint:startPoint];        <br> <br>    createBoltPath(startPoint.x, startPoint.y, endPoint.x, endPoint.y, displace, path);<br> <br>    SKShapeNode *bolt = [SKShapeNode node];<br>    bolt.path = path.CGPath;<br>    bolt.strokeColor = [SKColor whiteColor];<br>    bolt.lineWidth = 0.5f;<br>    bolt.antialiased = NO;<br>    [self addChild:bolt];<br> <br>    SKShapeNode *shadowNode = [[SKShapeNode alloc] init];<br>    shadowNode.path = path.CGPath;<br>    shadowNode.strokeColor = [SKColor colorWithRed:0.702 green:0.745 blue:1 alpha:1.0];<br>    shadowNode.lineWidth = 0.5f;<br>    shadowNode.alpha = 0.4;<br>    shadowNode.glowWidth = 5.f;<br>    [self addChild:shadowNode];<br>}<br> <br>- (void)createBoltWithPath:(UIBezierPath*)path {    <br>    BoltNode *bolt = [[BoltNode alloc] initWithBezierPath:path lifetime:0.5f];<br>    [self addChild:bolt];<br>}</pre><p>Defining <strong>SKShapeNode</strong> with <strong>UIBezierPath</strong> seems very simple, and result looks nice and realistic, but if you use a lot of such nodes, FPS dramatically drops. That didn’t suit me, so I came to the second approach: using CAShapeLayer.</p><h3>CAShapeLayer.</h3><p><strong>CAShapeLayer</strong> allows us to draw a path on our view’s <strong>CALayer</strong>. Moreover, it offers a shadow setting for the path out of the box: by using <em>shadowColor</em>, <em>shadowOffset</em>, <em>shadowRadius</em> and <em>shadowOpacity</em> properties. Ok, let’s try that!</p><pre>- (void)addBoltWithStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {<br>    // Dynamically calculating displace<br>    // Distance between two points<br>    float hypot = hypotf(fabsf(endPoint.x - startPoint.x), fabsf(endPoint.y - startPoint.y));<br>    // hypot/displace = 4/1<br>    float displace = hypot*0.25;<br> <br>    UIBezierPath *path = [UIBezierPath bezierPath];<br>    [path moveToPoint:startPoint];        <br> <br>    createBoltPath(startPoint.x, startPoint.y, endPoint.x, endPoint.y, displace, path);<br> <br>    CAShapeLayer *shapeLayer = [CAShapeLayer layer];<br>    shapeLayer.path = bezierPath.CGPath;<br>    shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];<br>    shapeLayer.lineWidth = 1.f;<br>    shapeLayer.fillColor = [UIColor clearColor].CGColor;<br>    shapeLayer.zPosition = 20;<br>    shapeLayer.shadowColor = [UIColor colorWithRed:0.702 green:0.745 blue:1 alpha:1.0].CGColor;<br>    shapeLayer.shadowOffset = CGSizeMake(0, 0);<br>    shapeLayer.shadowRadius = 7.f;<br>    shapeLayer.shadowOpacity = 1.f;<br>    shapeLayer.shouldRasterize = YES;<br>    [self.view.layer addSublayer:shapeLayer];<br>}</pre><p>Using <strong>CAShapeLayer</strong> seems much more efficient than <strong>SKShapeNode</strong>:</p><p>But there are several cons:</p><ul><li>The shadow looks very pale and unnatural</li><li>You cannot change <em>zPosition</em> of <em>shapeLayer</em> on <strong>SKScene</strong>. Thus you cannot place any of your <strong>SKNodes</strong> above <em>shapeLayer</em>.</li></ul><p>I googled about other methods of lightning generation and found a great article <a href="http://gamedevelopment.tutsplus.com/tutorials/how-to-generate-shockingly-good-2d-lightning-effects--gamedev-2681">“How to Generate Shockingly Good 2D Lightning Effects” by Michael Hoffman</a>. He has written his project using C# and XNA, so I decided to make the same trick with using Objective-C and Sprite Kit’s <strong>SKSpriteNode</strong>!</p><h3>SKSpriteNode.</h3><p>First, we need to draw our building blocks: a half-circle image and a lightning segment. Here is what I got so far:</p><p>Second, Michael uses his own method to generate a lightning bolt path, but Midpoint Displacement algorithm seems more realistic for me, so I decided to keep using it. We don’t need <strong>UIBezierPath</strong> with this approach, so let’s slightly change the code of createBolt function:</p><pre>void createBolt(float x1, float y1, float x2, float y2, float displace, NSMutableArray *pathArray) {<br>    if (displace &lt; 1.8f) {<br>        CGPoint point = CGPointMake(x2, y2);<br>        [pathArray addObject:[NSValue valueWithCGPoint:point]];<br>    }<br>    else {<br>        float mid_x = (x2+x1)*0.5f;<br>        float mid_y = (y2+y1)*0.5f;<br>        mid_x += (arc4random_uniform(100)*0.01f-0.5f)*displace;<br>        mid_y += (arc4random_uniform(100)*0.01f-0.5f)*displace;<br>        createBolt(x1, y1, mid_x, mid_y, displace*0.5f, pathArray);<br>        createBolt(mid_x, mid_y, x2, y2, displace*0.5f, pathArray);<br>    }<br>}</pre><p>Third, let’s create a special <strong>SKNode</strong> called LightningLine, which represents one single line of our path:</p><pre>@interface LightningLine : SKNode<br> <br>@property (nonatomic) CGPoint startPoint;<br>@property (nonatomic) CGPoint endPoint;<br>@property (nonatomic) float thickness;<br> <br>- (instancetype)initWithStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;<br>- (void)draw;<br>+ (void)loadSharedAssets;<br> <br>@end<br> <br>@implementation LightningLine<br> <br>- (instancetype)initWithStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {<br>    if (self = [super init]) {<br>        self.startPoint = startPoint;<br>        self.endPoint = endPoint;<br>        self.thickness = 1.3f;<br>    }<br>    return self;<br>}<br> <br>- (void)draw {<br>    const float imageThickness = 2.f;<br>    float thicknessScale = self.thickness / imageThickness;<br>    CGPoint startPointInThisNode = [self convertPoint:self.startPoint fromNode:self.parent];<br>    CGPoint endPointInThisNode = [self convertPoint:self.endPoint fromNode:self.parent];<br>    float angle = atan2(endPointInThisNode.y - startPointInThisNode.y,<br>                        endPointInThisNode.x - startPointInThisNode.x);<br>    float length = hypotf(fabsf(endPointInThisNode.x - startPointInThisNode.x),<br>                         fabsf(endPointInThisNode.y - startPointInThisNode.y));<br> <br>    SKSpriteNode *halfCircleA = [SKSpriteNode spriteNodeWithTexture:[self halfCircle]];<br>    halfCircleA.anchorPoint = CGPointMake(1, 0.5);<br>    SKSpriteNode *halfCircleB = [SKSpriteNode spriteNodeWithTexture:[self halfCircle]];<br>    halfCircleB.anchorPoint = CGPointMake(1, 0.5);<br>    halfCircleB.xScale = -1.f;<br>    SKSpriteNode *lightningSegment = [SKSpriteNode spriteNodeWithTexture:[self lightningSegment]];<br>    halfCircleA.yScale = halfCircleB.yScale = lightningSegment.yScale = thicknessScale;<br>    halfCircleA.zRotation = halfCircleB.zRotation = lightningSegment.zRotation = angle;<br>    lightningSegment.xScale = length*2;<br> <br>    halfCircleA.blendMode = halfCircleB.blendMode = lightningSegment.blendMode = SKBlendModeAlpha;<br> <br>    halfCircleA.position = startPointInThisNode;<br>    halfCircleB.position = endPointInThisNode;<br>    lightningSegment.position = CGPointMake((startPointInThisNode.x + endPointInThisNode.x)*0.5f,<br>                                            (startPointInThisNode.y + endPointInThisNode.y)*0.5f);<br>    [self addChild:halfCircleA];<br>    [self addChild:halfCircleB];<br>    [self addChild:lightningSegment];<br>}<br> <br>+ (void)loadSharedAssets {<br>    static dispatch_once_t onceToken;<br>    dispatch_once(&amp;onceToken, ^{<br>        sHalfCircle = [SKTexture textureWithImageNamed:@&quot;half_circle&quot;];<br>        sLightningSegment = [SKTexture textureWithImageNamed:@&quot;lightning_segment&quot;];<br>    });<br>}<br> <br>static SKTexture *sHalfCircle = nil;<br>- (SKTexture*)halfCircle {<br>    return sHalfCircle;<br>}<br> <br>static SKTexture *sLightningSegment = nil;<br>- (SKTexture*)lightningSegment {<br>    return sLightningSegment;<br>}<br> <br>@end</pre><p><em>loadSharedAssets</em> method loads our images to static variables, so it must be called before we initialize a node. The best way to call it is <strong>SKScene</strong>’s init method.</p><pre>- (instancetype)initWithSize:(CGSize)size {<br>    if (self = [super initWithSize:size]) {<br>        [LightningLine loadSharedAssets];<br>    }<br>    return self;<br>}</pre><p>Finally, here is a method, that does all magic:</p><pre>- (void)drawBoltFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint {<br>    // Dynamically calculating displace<br>    float hypot = hypotf(fabsf(endPoint.x - startPoint.x), fabsf(endPoint.y - startPoint.y));<br>    // hypot/displace = 4/1<br>    float displace = hypot*0.25;<br>    float angle = atan2(endPoint.x - startPoint.x, endPoint.y - startPoint.y);<br> <br>    NSMutableArray *pathArray = [NSMutableArray array];<br>    [pathArray addObject:[NSValue valueWithCGPoint:startPoint]];<br>    createBolt(startPoint.x, startPoint.y, endPoint.x, endPoint.y, displace, pathArray);<br>    //    NSMutableArray *boltLines = [NSMutableArray array];<br>    for (int i = 0; i &lt; pathArray.count - 1; i = i + 1) {<br>        LightningLine *line = [[LightningLine alloc] initWithStartPoint:((NSValue *)pathArray[i]).CGPointValue <br>                                                               endPoint:((NSValue *)pathArray[i+1]).CGPointValue];<br>        [self addChild:line];<br>        [line draw];<br>    }<br>}</pre><p>I prepared sample Xcode project, which includes all of the approaches described here: <a href="https://github.com/andrew8712/SpriteKitLightning">https://github.com/andrew8712/SpriteKitLightning</a></p><p>Here is Swift version: <a href="https://github.com/andrew8712/SpriteKitLightning-Swift">https://github.com/andrew8712/SpriteKitLightning-Swift</a></p><p>You can use it however you want to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aba4963698d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DCKit: how to convert Xcode IB to WYSIWYG-editor]]></title>
            <link>https://agordeev.medium.com/dckit-how-to-convert-xcode-ib-to-wysiwyg-editor-800d7dd74e6b?source=rss-5946a4eff410------2</link>
            <guid isPermaLink="false">https://medium.com/p/800d7dd74e6b</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Andrey Gordeev]]></dc:creator>
            <pubDate>Wed, 10 Feb 2016 16:16:57 GMT</pubDate>
            <atom:updated>2016-02-10T16:16:57.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8tTBGQDBv9zUxmuaFN8Bw.png" /></figure><p>I’m keep looking for ways of making the process of creating iOS apps a bit simpler and faster. I’m also trying to avoid code related to UI elements as much as possible, and move this effort to Xcode Interface Builder. Fortunately, Xcode offers some nice possibilities for this.</p><p>I created a useful set of UI controls called <a href="https://github.com/andrew8712/DCKit"><strong>DCKit</strong></a>. They use <strong>IBInspectable</strong>/<strong>IBDesignable</strong> features Apple introduced earlier in Xcode 6. <strong>DCKit</strong> gives you much more powerful controls than a standard <em>UIButtons</em>/<em>UITextFields</em> etc. Using <strong>DCKit</strong> you would be able to modify a control’s properties, which are not exposed to Interface Builder in usual cases.</p><p>E.g. it’s a common case when you need to create a bordered text field, or change placeholder’s text color. With <strong>DCKit</strong>, you would be able to do this with 2 clicks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*5cpWSWn7NO4EOMgj5lu1aA.gif" /></figure><p>Here is a video for further reference:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwMucSI5ESAU%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwMucSI5ESAU%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwMucSI5ESAU%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/79cf71c340033d9df06ba786e5717c41/href">https://medium.com/media/79cf71c340033d9df06ba786e5717c41/href</a></iframe><p>No need to write boilerplate code in your view controllers anymore! <strong>DCKit</strong> will handle this for you.</p><p>This library includes many useful controls, but there are couple essentials, widely used in my projects:</p><h4>DCHairlineView</h4><p>This view allows you to draw a thin line under a section of controls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*hOumvy80hzepOBWYUVoBmQ.png" /></figure><p>It has a customizable thickness and color.</p><h4>DCMandatoryTextField</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*NLhsomHJOQG7R0zjODThuA.png" /></figure><p>Very often we want the user to enter a value before he can proceed. <em>DCMandatoryTextFields</em> have <em>isValid()</em> method, which changes border color to red (or whatever you specify) if the field is empty.</p><h4>DCMandatoryEmailTextField</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*QUn6Dwezg0y8-6Jfrll6HQ.png" /></figure><p>This is a subclass of <em>DCMandatoryTextField</em>. It checks a value the user is entering, and if it doesn’t match the email regexp, it changes border color to red on the fly.</p><p>The library is absolutely free for use and available on <strong>Github</strong>: <a href="https://github.com/andrew8712/DCKit">https://github.com/andrew8712/DCKit</a>. Contributors are welcomed!</p><p><strong>DCKit</strong> helps Xcode to be more WYSIWYG-like. From my experience, this speeds up the development process! ;-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800d7dd74e6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>