Swift 3.0: How to call a method on main thread?

Hi guys, long time no posting on my blog, from now on I’m going to post a lot of useful stuff about Swift 3.0+.

Most of the time when we are building an app we need to make a method call on main thread even if we are not actually on main thread.

The most common case is when we are using tableview and need to refresh its content like this:

self.tableView?.reloadData();

If you run the code above it won’t work properly or it will show an error, because you need to run it in the main thread. To make this code actually work, you need to call it like this:

 

        DispatchQueue.main.async(execute: {() -> Void in

             self.tableView?.reloadData();

        })

DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.

Basically the code above is calling the class DispatchQueue with the property main, which means you want to call the method inside the main thread, this method won’t return anything.

That’s it, see you in the next post.

How to send Push Notifications from a Mac OS X – Push Robot

Mobile Developers love to imagine the users of their apps using the app all day. Push notifications allows developers to reach their users and perform small tasks even when users aren’t actively using an app.

Google has created Firebase Cloud Messaging for helping developers sending Push Notifications to their apps. You just need to login to your Google account and after some setup, you can easily send push notifications. What if you could send notifications from your Mac ? With this in mind, I’ve decided to create a Mac OS X App called Push Robot.

Push Robot allows you to send Push Notifications to your apps using FCM, all you need is the Server Key and the Topic or Device’s Token(to send push notifications to a single app).

Screen Shot 2017-04-12 at 07.54.21

To get the Server Key:

  1. click the settings icon/cog wheel next to your project name at the top of the new Firebase Console
  2. Click Project settings
  3. Click on the Cloud Messaging tab
  4. The key is right under Server Key

Now you can send a push notification to a topic which can reach millions of users or for specific users using the device’s token.

That’s all for today, I hope you guys enjoy the app.

See ya!

How to build an API using Rails – Part 1

The Rails 5 is out, and of course it came with a lot of new features and improvements, on this tutorial I’m going to cover the Rails API feature.

With all the Javascript stuff coming out, we have a lot of tools for building APIs these days, we have Express, Sails Js and many others. How about Ruby Developers? The most cool feature of Rails 5 is Rails API.

Rails::API is a subset of a normal Rails application, created for applications that don’t require all functionality that a complete Rails application provides. It is a bit more lightweight, and consequently a bit faster than a normal Rails application. The main example for its usage is in API applications only, where you usually don’t need the entire Rails middleware stack nor template generation.

Before you starting doing something you should download the most recent version of Ruby and Rails. I’d recommend using RVM for managing many versions of Ruby.

With all set the first command you should run is:

rails new rails_api_tutorial –api

This command will generate only the basic structure for building an API. It will make the ApplicationController inherit from ActionController::API instead of ActionController::Base. It will also configure the generators to skip generating views, helpers and assets when you generate a new resource.

The next step is to setup the testing stuff like: Rspec, FactoryGirl, Shoulda-Matchers and Rails Controller Testing.

After you adding all those gems your Gemfile should looks like this:

bildschirmfoto-2017-02-02-um-08-22-34

Hit bundle install to install those gems, and check the documentation of each one for more information about putting them to work.

After that you should create a folder called models inside of the spec/ folder, which will contain all the model specs of the API.

With all set, now we will create the first model spec of the application. Inside the spec/models folder create a Ruby file called post_spec.rb

The things the should be tested on model are: Table Fields, Validations, Relationships and any method you’d create. 

We are going to create a simple table for handling our posts, but first we need to create the spec for it:

spec/models/post_spec.rb

bildschirmfoto-2017-02-02-um-09-00-14

If we run this spec it will shows an error, because we haven’t implemented the Post model yet. Let’s do it:

bildschirmfoto-2017-02-02-um-09-13-08

We also need to create a migration with all the fields. For creating a migration run:

rails g migration post

After that, open the migration and add the fields:

bildschirmfoto-2017-02-02-um-09-39-24

Now you can migrate:

rails db:migrate

And prepare the migration for the tests:

rails db:test:prepare

After all you can run the command:

rspec

And all the tests should  pass:

bildschirmfoto-2017-02-02-um-09-39-53

The first part of this tutorial we covered:

  • The creation of an API only Rails Application
  • The setup of all the testing stuff
  • The creating of the Post model

On the next part of this tutorial I’m going to cover about controllers, how to test them and so on.

The source code of this tutorial is available on my Github: https://goo.gl/7Gr8WC

Do you like this post ? Would you mind to follow it ?

See you guys on the next part.

How to solve: Sorry, you can’t use byebug without Readline (Mac OS)

Byebug is a nice gem for debugging Ruby 2.

The most common problem to happen using this gem is the error: ‘Sorry, you can’t use byebug without Readline‘ , lucky for those running Mac OS, this issue can be simply solved by using this command on terminal:

ln -s /usr/local/opt/readline/lib/libreadline.dylib /usr/local/opt/readline/lib/libreadline.6.dylib

How to get the full path image url with carrierwave gem

In this post I’m going to cover how to get the full path url of an uploaded image using carrierwave gem.

By default carrierwave stores the uploaded images at /uploads/model_name/id/image.png

If you request the image url from the database it will only return the /uploads/model_name/id/image.jpg directory.

What if you need the full path ? Like: http://www.mysite.com/uploads/model_name/id/image.jpg

The only thing you need to do is to to set the asset_host in your development/production environment:Captura de Tela 2016-06-05 às 07.56.20.png

After that you need to restart your server and now you can get the full path of the image.

Feel free to ask questions and make suggestions 🙂

See you guys in the next time.

Shoucast Streaming in iOS (Objective-C)

In this post I’m going to cover how to build an iOS app that streams songs from Shoutcast server.

  1.  Open your XCode and Create a new project, select Single View Application and click in Next

Captura de Tela 2015-12-01 às 22.18.42

2. Name your app for Shoutcast, and then select Objective-C, and click in Next

Captura de Tela 2015-12-01 às 22.18.58

3. Create a button and name it play. This button will start the streaming

Captura de Tela 2015-12-01 às 22.26.59

4. Go to View->Assistent Editor->Show Assitent Editor

Captura de Tela 2015-12-01 às 22.27.39

5. Create an action called playMusic like the picture below:

Captura de Tela 2015-12-01 às 22.32.23

6. Open your ViewCotroller.h to create a property called myStreaming(you should create this property as strong, if you don’t do this the streaming will stop after 2 seconds)

Captura de Tela 2015-12-01 às 22.35.41

7. Now go to your ViewController.m and inside the method playMusic you should call the property you defined in your h file.

The First thing you need to have is the streaming URL (shoucast’s urls should have the address and the port), then your need to init the streaming property, after that you should define the source type, in our case is streaming, after all you just need to set shouldAutoPlay to NO and prepare to play the streaming and finally play.

– (IBAction)playMusic:(id)sender {    

 NSURL *myUrl = [NSURL  URLWithString:@”http://colinawebradio.com.br:9986″];

 self.myStreaming = [[MPMoviePlayerController alloc] initWithContentURL:myUrl];

  self.myStreaming.movieSourceType =         MPMovieSourceTypeStreaming;

   self.myStreaming.shouldAutoplay = NO;

   [self.myStreaming prepareToPlay];

   [self.myStreaming play];

}

After all, run your app and listen to the radio 🙂

That’s all, thanks :).

If you have any questions, feel free to ask.

See you guys next time!

Cpf_Validation Gem

Some days ago I released my first gem for CPF validation.

I’ve seen many gems which do the same but the authors seem to no update them.

You can help me to improve this gem by sending a pull request on github: https://github.com/GabrielLidenor/cpf_validation

Installation

As gem:

# in Gemfile
gem 'cpf_validation'

# Run bundler
$ bundle install

Usage

Validating a CPF attribute:

class Patient < ActiveRecord::Base
  validates_cpf :cpf_attr
  # or
  validates :cpf_attr, :cpf => true
end

Validating an attribute that can store CPF:

class Customer < ActiveRecord::Base
  validates_cpf :cpf_attr
  # or
  validates :cpf_attr, :cpf => true
end

Regular validation options:

:allow_nil   - Allows a nil value to be valid
:allow_blank - Allows a nil or empty string value to be valid
:if          - Executes validation when :if evaluates true
:unless      - Executes validation when :unless evaluates false
:on          - Specifies validation context (e.g :save, :create or :update). Default is :save