Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all 4373 articles
Browse latest View live

Swift Algorithm Club: Swift Depth First Search

$
0
0

SwiftAlgClub-DepthFirstSearch

The Swift Algorithm Club is an open source project, where we as a community implement popular data structures and algorithms in Swift.

Every month, the Swift Algorithm Club team will feature a data structure or algorithm from the club in a tutorial format. If you want to learn more about algorithms and data structures, follow along with us!

In this tutorial you’ll walk through a popular search and pathfinding algorithm: depth-first search.

This tutorial assumes you have read our Swift Graphs with Adjacency Lists and Swift Stack Data Structure or have the equivalent knowledge.

If you have been following along with our tutorial series, be sure to check out our breadth first search tutorial; another Swift pathfinding algorithm.

Getting Started

Have ever you seen the movie “Honey, I Shrunk the Kids“?

Imagine yourself being shrunk down to the size of an ant. You fall into an ant nest, and have to find your way out. What strategy are you going to use?

One great algorithm for solving maze problems like this is the Depth-first search algorithm, first developed by Charles Pierre Trémaux.

In this algorithm, you explore a branch as far as possible until you reach the end of the branch. At that point, you backtrack (go back a step), and explore the next available branch, until you find a way out.

In this tutorial you will explore how the depth-first search algorithm works in Swift, and how it differs from Breadth-first search.

There are many use cases for depth-first search such as:

  1. Topological sorting
  2. Detecting a cycle
  3. Pathfinding
  4. Finding connected components in a sparse graph
  5. And many more!

Today you will gain an understanding of depth-first search in Swift through pathfinding.

Traversing Breadth-First Search vs Depth-First Search

Imagine the graph below represents a maze, where S is the start location, and E is the end of the maze. Below shows a breadth-first search traversal of the maze.

On each vertex of the graph, breadth-first search visits every vertex’s immediate neighbors before going to the next. Hence the “breadth” of the traversal.

Next shows how depth-first search traverses the maze.

Assuming that the algorithm will always traverse the left side first before the right. Depth-first search will start exploring all the vertices on the left-most branch. If the end of the maze is not found, the algorithm will backtrack to the previous vertex, till it finds another path to explore.

For example once node D reaches node G, node G has no other neighbour, hence the backtrack to node D’s next available neighbour node F. Hence the “depth” of the traversal.

Implementing Depth-First Search

Let’s see what the depth-first search algorithm looks like in Swift.

Start by downloading the starter playground for this tutorial, which has the data structures for a Swift adjacency list and Swift stack included in the Sources group.

Included in the playgrounds is a sample graph used to test the implementation. If you don’t see the diagram, go to Editor > Show Raw Markup to enable it.

Note: If you’re curious how the Swift adjacency list and stack data structures work, you can see the code with View\Navigators\Show Project Navigator. You can also learn how to build these step by step in our Swift Graphs with Adjacency Lists and Swift Stack tutorials.

Question to Solve

Given a directed or undirected graph, use depth-first search to find a path between two vertices.

Example

Given the following graph, find a path from S to E:

The path should be S-A-B-D-F-E

Let’s start the implementation:

Open up the DepthFirstSearch playgrounds, and add the following:

func depthFirstSearch(from start: Vertex<String>, to end: Vertex<String>, graph: AdjacencyList<String>) -> Stack<Vertex<String>> { // 1
  var visited = Set<Vertex<String>>() // 2
  var stack = Stack<Vertex<String>>() // 3
 
  // TODO: More code here...
 
  return stack // 4
}

Let’s review the snippet above:

  1. Defines a function called depthFirstSearch(_:), where it takes a start vertex, an end vertex, and the graph you will traverse.
  2. Creates a set to store all the vertices that have been visited. This is so we prevent infinite loops.
  3. Creates a stack to store a potential path from the start to end vertex.
  4. Once the depth-first search completes, the stack will contain the path.

After the TODO, add the following:

stack.push(start)
visited.insert(start)

This initiates the depth-first search by pushing the start node, and marking the start node as visited. Next the following code right after:

outer: while let vertex = stack.peek(), vertex != end { // 1
 
  guard let neighbors = graph.edges(from: vertex), neighbors.count > 0 else { // 2
    print("backtrack from \(vertex)")
    stack.pop()
    continue
  }
 
  for edge in neighbors { // 3
    if !visited.contains(edge.destination) {
      visited.insert(edge.destination)
      stack.push(edge.destination)
      print(stack.description)
      continue outer
    }
  }
 
  print("backtrack from \(vertex)") // 4
  stack.pop()
}

Let’s review section by section:

1. The outer loop.

outer: while let vertex = stack.peek(), vertex != end { }

The goal is to find a path from the start vertex to the end vertex. So while the stack is not empty, the path has not been found. So begin peeking into the stack’s top vertex, and as long as the vertex is not at the end, check the following:

2. Any neighbors?

guard let neighbors = graph.edges(from: vertex), neighbors.count > 0 else {
  print("backtrack from \(vertex)")
  stack.pop()
  continue
}

Check to see if the current vertex has any neighbors. If there are none, that means you reached a dead-end. So backtrack by popping the current vertex off the stack.

3. Yes, I have neighbors!

If the vertex has any edges, you are going to loop through each edge.

for edge in neighbors {
  if !visited.contains(edge.destination) { // 1
    visited.insert(edge.destination) // 2
    stack.push(edge.destination) // 3
    print(stack.description) // 4
    continue outer // 5
  }
}

Checking the following:

  1. As long as the neighbouring vertex has not been visited.
  2. Mark the vertex as visited.
  3. Push the vertex on the stack. This means that this vertex is a potential candidate for the final path.
  4. Print the current path.
  5. Continue to the outer while loop to branch off the vertex you just pushed. Restarting the whole process from before.

This is depth-first search in action, continuing from the left-most branch.

4. All edges visited.

print("backtrack from \(vertex)")
stack.pop()

So what happens if all the edges have been visited? If all the edges from the current vertex has been visited, that means we reached a dead-end. So backtrack and pop it off the stack.

Once the top of the stack contains the end vertex. You have found a path from start to finish!

Finally let’s test out the algorithm. Add the following line at the end of the playground:

print(depthFirstSearch(from: s, to: e, graph: adjacencyList))

This is all you need to implement depth-first search! You should see the following output at the bottom of the playground, displaying the path to the exit:

E
F
D
B
A
S

You think you have depth-first search algorithm nailed down?

Quiz

From vertex S to vertex C using depth-first search. How many backtracked vertices were there?

Solution Inside: Solution SelectShow>

Where To Go From Here?

Here is the final playground with all the code for the depth-first search algorithm in Swift.

There’s also a recursive version of depth-first search in the Swift Algorithm Club’s repository. So be sure to check that out!

I hope you enjoyed this tutorial on creating pathfinding algorithms with depth-first search in Swift! There are many applications with graphs and this is just one of them.

So stay tuned for many more tutorials from the Swift Algorithm club in the future. In the meantime, if you have any questions or comments, please join the discussion below.

The post Swift Algorithm Club: Swift Depth First Search appeared first on Ray Wenderlich.


Dependency Injection in Android with Dagger 2

$
0
0

Dagger-featureThe cry of “You must do dependency injection!” is heard throughout modern software development teams. With such an imposing name, Dependency Injection (or DI for short) can put a fright into any software developer.

It turns out that Dependency Injection is nowhere near as complex as its name implies, and is a key tool for building software systems that are maintainable and testable. In the end, relying on dependency injection will simplify your code quite a bit and also allow for a clearer path to writing testable code.

In this tutorial, you’ll update an existing app named DeezFoodz to use DI. The DeezFoodz app shows a list of foods obtained from USDA Food Composition Databases, found here. A user can tap on one of the foods and see the sugar content of the food along with a thumbs up or thumbs down on the amount of sugar.

dependency injection

The app uses common Android libraries and patterns such as Retrofit and Model-View-Presenter. You’ll use the popular Java/Android dependency injection framework Dagger 2 to perform DI within the app.

Here’s a quick peek at the detail screen in DeezFoodz:

dependency injection deezfoodz

Before you begin, visit the link under Gaining Access on the USDA site linked to above. You’ll need that API key in order to build and use the starter app.

Introduction

So, just what are what are dependencies? Any non-trivial software program is going to contain components that pass information and message calls back and forth between one another.

For example, when using an Object Oriented Programming language (such as Java on Android), objects will call methods on other objects that they have references to. A dependency is simply when one of the objects depends on the concrete implementation of another object.

From a practical perspective in Java code, you can identify a dependency in your code whenever you use the new keyword to instantiate one object within another. In such a case, you are fully responsible for creating and properly configuring the object that is being created. For example, in the following class A:

public class A {
  private B b;
  public A() {
    b = new B();
  }
}

An A instance creates its b field in its constructor. The A instance is fully dependent on the concrete implementation of B and on configuring the b field in order to use it properly.

This presents a coupling or dependency of the A class on the B class. If the setup of a B object is complex, all of that complexity will be reflected within the A class as well. Any changes necessary to configure a B object will have to be made within class A.

Should the B class depend itself on class C, which in turn depends on class D, all of that complexity will propagate throughout the code base and cause a tight coupling between the components of the application.

Dependency Injection is the term used to describe the technique of loosening the coupling just described. In the simple example above, only one tiny change is needed:

public class A {
  private B b;
  public A(B b) {
    this.b = b;
  }
}

Voilà — that’s dependency injection at its core! Rather than creating the b object in the A constructor, the b object is passed into or injected into A‘s constructor. The responsibility for configuring b is elsewhere, and the A class is simply a consumer of the B class.

The Dependency Inversion Principle

Dependency injection is often discussed in conjunction with one of the five SOLID principles of Object-Oriented Design: the Dependency Inversion principle. For a great introduction to the SOLID principles, particularly on Android, check out this post from Realm on Dependency Inversion.

The gist of the Dependency Inversion principle is that it is important to depend on abstractions rather than concrete implementations.

In the simple example above, this means changing B to a Java interface rather than a Java class. With this change, many different types of concrete B type objects that adhere to the B interface can be passed into the A constructor. This presents several key benefits:

  • Allows for the A class to be tested with various kinds of B objects.
  • Mock B objects can be used as needed in certain test scenarios.
  • Testing of A is independent of the implementation of B.

While often discussed together, dependency injection and the Dependency Inversion principle are not the same. Essentially, dependency injection is a technique that is used as part of adhering to the Dependency Inversion Principle.

Dagger 2

In the Java world, there are a number of frameworks that have been created to simplify the application of dependency injection. The frameworks remove a lot of the boilerplate code that can occur, and also provide a systematic way to apply dependency injection across a software system.

One of the earlier Java dependency injection frameworks was Guice, created at Google. The team at Square later developed the Dagger framework, targeted primarily at Android.

While a fantastic accomplishment, the initial Dagger framework had a few downsides. For example, performance issues due to runtime reflection and difficulty working with ProGuard.

As a result, the updated Dagger 2 framework was born, which produces simpler generated code and solves the performance issues by having injection occur at compile time.

The name “Dagger” is inspired in part by the nature of dependencies in software development. The web of dependencies that occur between objects such as A, B, C, …, create a structure called a Directed Acyclic Graph. Dagger and Dagger 2 are used to simplify the creation of such graphs in your Java and Android projects.

For the remainder of the tutorial, the term Dagger will refer to Dagger 2.

Enough theory! Time to start writing some code.

Getting Started

Download the starter project here.

Open the starter app in Android Studio. You’ll need Android Studio 2.2.2 or later. If you’re using a later version of Android Studio than 2.2.2 and are prompted to update your gradle version, go ahead and do so.

Also update the file Constants.java in the app package to replace the API_KEY constant with the key you obtained from the USDA web site.

Build and run the app in either an emulator or on a device to make sure you can build the starter project.

dependency injection Main Screen

The app consists of two screens. The first is a list of foods downloaded from USDA Food Composition Databases, again found here. Tapping on any item on the list shows a detail screen, which contains info on the sugar content on the food.

Examine the app project structure and existing classes. You’ll see that the app uses the Model-View-Presenter (MVP) pattern to structure the code, and also uses the Retrofit 2 library from Square as part of its networking layer to connect to the USDA API.

The subpackages in the main package are app, model, network, and ui. If you explore the ui package, you’ll see subpackages for the two screens. Each screen has classes for the view and presenter classes for the screen.

dependency injection project

By examining the app build.gradle file, you’ll also see that the app uses Butterknife for view binding, and a lightweight stream library for Java 8-like stream processing.

MVP

In case you’re unfamiliar with the MVP pattern, there are many good online resources for getting started.

MVP is similar to other structural patterns for implementing separation of concerns, such as Model-View-Controller and Model-View-ViewModel. In MVP on Android, your activities and fragments typically act as the view objects by implementing a view interface, and handle interaction of the app with the user.

The view passes on user actions to the presenter, which handles the business logic and interaction with data repositories, such as a server API or database. The model layer consists of the objects that make up the content of the app.

In the case of DeezFoodz, the FoodActivity class for the detail screen implements the FoodView interface. FoodActivity has a reference to a FoodPresenter interface, which controls access to model objects of type Food.

The use of Retrofit 2 is found in the UsdaApi class in the network package. This class defines the interface to the USDA API required by the app. There are two calls of type GET defined, one to retrieve a FoodzList and the other to get details on a particular Food object via a query parameter.

Note: Retrofit is a powerful type-safe HTTP client. It lets you represent the USDA REST API as Java interfaces. Retrofit simplifies the task of making synchronous or asynchronous requests to a web service, and turning the responses into Plain Old Java Objects (POJOs). For more information, see Android Networking Tutorial: Getting Started.

Dependencies in DeezFoodz

Open the FoodActivity class in the ui.food package. In its onCreate() method, there are several calls to create and configure a FoodPresenter:

presenter = new FoodPresenterImpl();
presenter.setView(this);
presenter.getFood(foodId);

Here, you create a concrete implementation of a FoodPresenter. Open FoodPresenterImpl.java and take a look at getFood(). Both a Retrofit object and a UsdaApi object are created and configured in getFood() using factory methods.

This creation of dependencies couple the model, view, and presenter layers too tightly. Swapping in a mock presenter for the view is impossible as written without updating the view code. The code for creating the Retrofit and UsdaApi objects is repeated between the two presenter implementations in the app: FoodPresenterImpl and FoodzPresenterImpl.

Next up, you’ll use Dagger to implement dependency injection in DeezFoodz and remove the coupling between layers as well as the code duplication.

Finally, it’s time to start writing some new code!

Configure the Project With Dagger 2

Open up the app build.gradle file and add the following Dagger dependencies to the app dependencies:

depencies {
  ...
  // Dependency Injection
  apt "com.google.dagger:dagger-compiler:2.2"
  compile "com.google.dagger:dagger:2.2"
  provided 'javax.annotation:jsr250-api:1.0'
  ...
}

The ellipses represent existing dependencies in the starter project. Android Studio will prompt you to sync your gradle files on this change, so please go ahead and do so to ensure that you’re including Dagger correctly. Notice that you are including an annotation library from javax, because many of the features of Dagger are provided by Java annotations.

Modules

The first annotation you’ll use is the @Module annotation. Start by creating a new package named dagger under the app main package, by right-clicking the main package and selecting New/Package:

dependency injection newpackage

Next, create a new file in the dagger package. Right-click dagger and select New/Java Class. Name the class AppModule.

dependency injection newclass

dependency injection Dagger Module

Add the following empty class to the new file:

@Module
public class AppModule {
}

Here, you’ve created a class named AppModule and annotated it with the Dagger @Module annotation. Android Studio should automatically create any necessary import statements for you, but if not, hit Alt-Enter to create them as needed.

The @Module annotation tells Dagger that the AppModule class will provide dependencies for a part of the application. It is normal to have multiple Dagger modules in a project, and it is typical for one of them to provide app-wide dependencies.

Add that capability now by inserting the following code within the body of the AppModule class:

private Application application;
 
public AppModule(Application application) {
  this.application = application;
}
 
@Provides
@Singleton
public Context provideContext() {
  return application;
}

You’ve added a private field to hold a reference to the application object, a constructor to configure application, and a provideContext() method that returns the application object. Notice that there are two more Dagger annotations on that method: @Provides and @Singleton.

The @Provides annotation tells Dagger that the method provides a certain type of dependency, in this case, a Context object. When a part of the app requests that Dagger inject a Context, the @Provides annotation tells Dagger where to find it.

Note: The method names for the providers, such as provideContext(), are not important and can be named anything you like. Dagger only looks at the return type.

The @Singleton annotation tells Dagger that there should only be a singleton instance of that dependency and removes a lot of the boilerplate singleton code for you.

Components

Now that you have a Dagger module that contains a dependency that can be injected, how do you use it?

That requires the use of another Dagger annotation, @Component. Start by creating a new Java file in the dagger package, and name it AppComponent.

Add the following code to the file (replace class with interface if needed):

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
}

You’ve told Dagger that AppComponent is a singleton component interface for the app. The @Component annotation takes a list of modules as an input, and you’ve added AppModule to the list.

The component is used to connect objects to their dependencies, typically by use of overridden inject() methods. It takes the place of the reflective object graph in the original version of Dagger. In order to use the component, it must be accessible from the parts of the app that need injection. Typically, that will happen from the app Application subclass, as follows.

First, add the following field and getter to DeezFoodzApplication:

private AppComponent appComponent;
 
public AppComponent getAppComponent() {
  return appComponent;
}

Now, you must initialize AppComponent. Do so by adding the following method to DeezFoodzApplication:

protected AppComponent initDagger(DeezFoodzApplication application) {
  return DaggerAppComponent.builder()
      .appModule(new AppModule(application))
      .build();
}

You’ll likely notice an error called out by Android Studio on DaggerAppComponent. That class has not yet been generated within the project. Choose Make Module ‘app’ from the Android Studio Build menu. This may produce compile errors, but will clear the error in the code.

Run Make Module ‘app’ again to clear the compile errors. Once done, you’ll then notice a deprecation warning on the appModule() method; that will be fixed shortly.

Finally, update onCreate() in DeezFoodzApplication to read as follows:

@Override
public void onCreate() {
  super.onCreate();
  appComponent = initDagger(this);
}

This initializes the appComponent field when the application first starts up.

dependency injection

Dependency Injection With Dagger 2

Add the following method declaration within the AppComponent interface:

void inject(FoodzActivity target);

Here, you’ve specified that the FoodzActivity class will require injection from AppComponent. You’re going to inject the presenter object into FoodzActivity.

Create a new class in the dagger package and name it PresenterModule. Add the following code into PresenterModule:

@Module
public class PresenterModule {
  @Provides
  @Singleton
  FoodzPresenter provideFoodzPresenter() {
    return new FoodzPresenterImpl();
  }
}

You’re specifying that a FoodzPresenter will be provided, and that the presenter returned will be the concrete implementation FoodzPresenterImpl.

Next, wire up PresenterModule with AppComponent by updating the @Component annotation in AppComponent to read:

@Component(modules = {AppModule.class, PresenterModule.class})

Finally, open up the FoodzActivity class in the ui.foodz package. First, add a new annotation @Inject onto the presenter field:

@Inject
FoodzPresenter presenter;

Then, remove the following creation of the presenter object in onCreate():

presenter = new FoodzPresenterImpl();

The @Inject annotation tells Dagger that you want it to do an injection of the presenter field.

Were you to run your app now, however, you would get a crash from a NullPointerException (NPE) on presenter. There is one last step to hook everything up.

Update onCreate() by adding the call to AppComponent.inject() as follows:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_foodz);
 
  ((DeezFoodzApplication)getApplication()).getAppComponent().inject(this);
 
  ButterKnife.bind(this);
  ...

You are getting the AppComponent from DeezFoodzApplication and asking it to inject all known dependencies into FoodzActivity. Since you annotated presenter with @Inject, Dagger will inject a concrete FoodzPresenter object into FoodzActivity.

Dagger knows that you defined provideFoodzPresenter() in the PresenterModule class, and uses it to create the injected FoodzPresenter object.

Build and run your app now. It should behave exactly as before, and you’ve avoided the NPE. You’ve just finished your first dependency injection with Dagger 2!

There is a general pattern that emerges based on the previous code changes. Think about the steps just taken to use Dagger dependency injection with FoodzActivity:

  • Add inject() in AppComponent with FoodzActivity argument.
  • Add provideFoodzPresenter() in PresenterModule.
  • Add @Inject annotation to FoodzPresenter presenter in FoodzActivity.
  • Add DeezFoodzApplication.getAppComponent().inject(this) in OnCreate() in FoodzActivity.

If you consider FoodzActivity as the target class, and FoodzPresenter as the source interface to be injected, then the above steps can be generalized as follows for any target class requiring source interfaces to be injected:

  • Add inject() in AppComponent with Target class argument.
  • Add @Provides annotated method in PresenterModule for each source object to be injected.
  • Add @Inject annotation to each Source member variable in Target class.
  • Add DeezFoodzApplication.getAppComponent().inject(this) in OnCreate() in Target class.

As a challenge, see if you can perform an injection of the FoodPresenter detail screen into FoodActivity in the ui.food package, which will include removing the following line of code:

presenter = new FoodPresenterImpl();

The steps are just the same as above for FoodzActivity. Use the pattern, and if you get stuck, check out the final project code at the end of this tutorial.

Injecting the Network Graph

In the app as written currently, both the list screen and detail screen presenters create their own network dependencies. In a typical app that uses Dagger 2 and Retrofit together, Retrofit will be provided by dependency injection.

Here you will see some of the many advantages of using dependency injection and Dagger 2, including:

  • Eliminating code duplication.
  • Eliminating the need for dependency configuration.
  • Automatic construction of a dependency graph.

Start by creating a new file in the dagger package, this time named NetworkModule, which starts off as follows:

@Module
public class NetworkModule {
}

What you’re looking to do here is to inject a UsdaApi object into the app’s presenter implementations, so that the presenters can call the API.

For example, if you look at the current FoodPresenterImpl, you see that UsdaApi depends on a Retrofit object, whereas creation of a Retrofit object requires a String for the base URL of the API as a well as a Converter.Factory object.

dependencies

Start by adding those two methods into NetworkModule along with a constant string:

private static final String NAME_BASE_URL = "NAME_BASE_URL";
 
@Provides
@Named(NAME_BASE_URL)
String provideBaseUrlString() {
  return Constants.BASE_URL;
}
 
@Provides
@Singleton
Converter.Factory provideGsonConverter() {
  return GsonConverterFactory.create();
}

There is a new Dagger annotation in play here, @Named. You are injecting a String object, and since String is such a common type to use in an Android app, you’ve taken advantage of the @Named annotation to specify a specific string to be provided. This same technique can be used for your own types if you need multiple variations injected.

Now that you have a String and a GsonConverterFactory, add the following to the bottom of NetworkModule:

@Provides
@Singleton
Retrofit provideRetrofit(Converter.Factory converter, @Named(NAME_BASE_URL) String baseUrl) {
  return new Retrofit.Builder()
    .baseUrl(baseUrl)
    .addConverterFactory(converter)
    .build();
}
 
@Provides
@Singleton
UsdaApi provideUsdaApi(Retrofit retrofit) {
  return retrofit.create(UsdaApi.class);
}

You’ve added the provides methods for both a Retrofit object and a UsdaApi object. This allows Dagger to construct a dependency graph, so that when an object asks for a UsdaApi object to be injected, Dagger will first provide a Retrofit object to use in provideUsdaApi(Retrofit retrofit).

Then, Dagger will continue walking up the graph to find a converter and baseUrl for provideRetrofit(Converter.Factory converter, @Named(NAME_BASE_URL) String baseUrl).

By using the @Singleton annotations, only one instance of the UsdaApi and Retrofit objects will be created and shared between both activities in the app.

Add your NetworkModule to AppComponent by updating the @Component annotation to the following:

@Component(modules = {AppModule.class, PresenterModule.class, NetworkModule.class})

Next, update the PresenterModule provide methods so that the presenter constructors are passed a Context:

@Provides
@Singleton
FoodzPresenter provideFoodzPresenter(Context context) {
  return new FoodzPresenterImpl(context);
}
 
@Provides
@Singleton
FoodPresenter provideFoodPresenter(Context context) {
  return new FoodPresenterImpl(context);
}

Add the following two inject methods into AppComponent:

void inject(FoodzPresenterImpl target);
void inject(FoodPresenterImpl target);

Next, update FoodzPresenterImpl and FoodPresenterImpl to add the following constructors:

public FoodzPresenterImpl(Context context) {
  ((DeezFoodzApplication)context).getAppComponent().inject(this);
}
public FoodPresenterImpl(Context context) {
  ((DeezFoodzApplication)context).getAppComponent().inject(this);
}

Add the following field injection to both classes:

@Inject
UsdaApi usdaApi;

Now that you’re injecting UsdaApi into the two presenter implementations, remove the following duplicated code from each:

Converter.Factory converter = GsonConverterFactory.create();
 
Retrofit retrofit = new Retrofit.Builder()
  .baseUrl(Constants.BASE_URL)
  .addConverterFactory(converter)
  .build();
 
UsdaApi usdaApi = retrofit.create(UsdaApi.class);

You’ve successfully injected the UsdaApi dependency into both presenters, which allowed you to remove the duplicated creation of the GsonConverterFactory and Retrofit objects.

Build and run your app one final time. Once again, you should see no change in the app behavior, but you’ve successfully applied dependency injection and made your app both more maintainable and testable!

Where to Go From Here?

You can download the final project here.

The changes you made to DeezFoodz may seem like a lot of work. But the utility of dependency injection and a framework like Dagger 2 become most evident in real-world production apps, where the dependency graph can get very complex.

Dagger 2 and dependency injection become especially useful when implementing proper testing into your app, allowing mock implementations of back-end APIs and data repositories to be used in testing.

There’s much more to learn about in Dagger 2 and its usage, including:

  • Scopes
  • Subcomponents
  • Testing with Mockito

There are many great resources out there on the interwebs to dive into these topics. As you do, happy injecting!

If you have any questions or comments, please join the discussion below!

The post Dependency Injection in Android with Dagger 2 appeared first on Ray Wenderlich.

In-App Purchases: Auto-Renewable Subscriptions Tutorial

$
0
0
Learn all about auto-renewable subscriptions!

Learn all about auto-renewable subscriptions!

Apple announced a new feature before WWDC 2016: auto-renewable subscriptions. Aside from the obvious benefit to your pocketbook, there’s more to love about this new feature.

With a normal purchase, Apple takes a 30 percent cut of the revenue and you get the remaining 70 percent. When a user signs up for an auto-renewable subscription for a year, however, Apple only takes 15 percent and you get 85 percent.

This is excellent news for developers that offer subscription-based content!

You’ll learn how to set up auto-renewable subscriptions and offer them to users through the App Store in this hands-on iOS tutorial.

Prerequisites

Before working through this tutorial, you should be familiar with in-app purchases. If you’re not, you should read our In-App Purchases: Non-Renewing Subscriptions tutorial — at least until you reach the Implementing Non-Renewing Subscriptions: Overview section.

You also need access to a paid iTunes Connect account and an actual device; unfortunately, the simulator and free Apple developer account won’t suffice.

Getting Started

Selfie Friday is a weekly ritual for RW team members. It’s a special day where we post our most candid selfies in a private Slack channel. You wouldn’t believe how impeccable Ray looks each week! ;]

Until now, these photographic gems have only been available to team members. No More! These selfies should be available to everyone — at a price.

In this iOS tutorial, you’ll create an app that offers users these auto-renewable subscriptions:

  • $0.99/week for 1 selfie each week
  • $2.99/month for 1 selfie each week with a 1-week trial period
  • $1.99/week for all selfies each week
  • $5.99/month for all selfies each week with a 1-week trial period

Total bargain, right?!

The app uses a simple collection view to display the selfies. Per App Store review Guidelines — which you should read after you’re done here — a user must get access to your content as soon as she subscribes.

You’ll use a mock “server” that provides selfies based on a user’s subscription status. It is part of this tutorial so that you can focus on auto-renewable subscriptions and not on the app design.

This server acts as a go-between from your phone to the App Store sandbox and it works around the nuances of sandboxing for auto-renewable subscriptions. In particular, the sandbox simulates subscription renewal at an accelerated rate. This way, you won’t need to wait weeks to test your app.

The table below shows how actual durations translate to sandbox durations:

auto-renewable subscriptions AppStoreSandboxTestingTimes

Download the starter project and open RW Selfies.xcodeproj.

Select the blue RW Selfies project folder in the project navigator, and then RW Selfies under the Targets.

Change the Bundle Identifier to something unique — for example, com.yourcompanyaddress.selfies.

In the Signing section, check Automatically Manage Signing, and then select your paid development team. Xcode should create a provisioning profile and signing certificate for you.

Build and run on your actual device. Remember that you need a device — the simulator might get you started but won’t take you all the way through this tutorial.

auto-renewable subscriptions  RW Selfies Landing Screen

You’ll then see the app’s landing screen. Tap Subscribed? Come on in….

RWSelfiesStarterProjectScreen2

Wait! Weren’t you supposed to subscribe to see the selfies?

The starter app is generous. Even though you haven’t purchased a subscription, the starter project gives you unlimited access to the first week’s content. Don’t worry about losing revenue to “lookee-lous” — you’ll change this setting to prevent giving away this incredibly valuable content for free! ;]

Introducing StoreKit

Similar to other areas of iOS development, there is a “kit”. StoreKit allows you to communicate with iTunes Connect and request in-app purchase information. It also handles requests for payments and processing.

Before you can leverage StoreKit within the app, however, you need to set up four in-app subscription options on iTunes Connect.

Creating Auto-Renewable Subscriptions

First, you need to create an app for this tutorial on iTunes Connect, so sign into iTunes Connect with your paid developer account.

Select My Apps from the dashboard, click the + button and select New App from the drop-down menu.

auto-renewable subscriptions itc-add-app

Enter the following values for this app:

  • Platforms: iOS
  • Name: RW Selfies – [Your Name] (or something else that’s unique)
  • Primary Language: English (U.S.)
  • Bundle ID: Select the Bundle ID you entered earlier in Xcode
  • SKU: Enter something unique across all your apps — use your Bundle ID if you’re not sure what to use

Click Create to go to the app’s configuration screen.

Select the Features tab near the top-left corner of the navigation area, and then click the + button next to In-App Purchases (0).

auto-renewable subscriptions  itc-add-iap

Pick the option for Auto-Renewable Subscription.

Note: If you don’t see an option for Auto-Renewable Subscription, you probably need to complete some contracts for your account.

Press Cancel and select My Apps from the top-left part of the screen. Then pick Agreements, Tax, and Banking from the options.

Make sure all the contracts are complete, especially the Paid Applications contract.

When you’re done, the status may show as “Processing”. Even so, you should be able to return to the In-App Purchases page and create a new Auto-Renewable Subscription.

Enter the following values for the first purchase option:

  • Reference Name: All Access Weekly
  • Product ID: [Your Bundle ID].sub.allaccess (replace [Your Bundle ID] with your bundle ID from Xcode, which makes this identifier globally unique)
  • Subscription Group Reference Name: Selfies

Click Create, then you’ll go to the in-app configuration page, where you should enter the following values:

  • Cleared for Sale: Check the box
  • Duration: 1 week
  • Free Trial: None
  • Starting Price: 1.99 USD, and accept the auto-selected values for all territories
  • Localizations: Add English (U.S.)
  • Subscription Display Name: All Access (Weekly)
  • Description: You will be able to view all the selfies from RayWenderlich.com team members each week. This subscription recurs weekly.

auto-renewable subscriptions itc-setup-first-sub

You can skip Review Information during this tutorial, but don’t skip it when you’re working with a real app.

Press Save to complete the subscription setup.

One down, three to go. Using the values below, repeat the process to create the second, third and fourth subscription options.

Second Subscription Values

  • Reference Name: All Access Monthly
  • Product ID: [Your Bundle ID].sub.allaccess.monthly
  • Subscription Group Reference Name: Selfies
  • Cleared for Sale: Check the box
  • Duration: 1 Month
  • Free Trial: 1 Week
  • Starting Price: 5.99 USD
  • Localizations: Add English (U.S.)
  • Subscription Display Name: All Access (Monthly)
  • Description: You will be able to view all selfies of RayWenderlich.com team members each week. This subscription recurs monthly and has a one-week trial period.

Third Subscription Values

  • Reference Name: One a Week Weekly
  • Product ID: [Your Bundle ID].sub.oneaweek
  • Subscription Group Reference Name: Selfies
  • Cleared for Sale: Check the box
  • Duration: 1 Week
  • Free Trial: None
  • Starting Price: 0.99 USD
  • Localizations: Add English (U.S.)
  • Subscription Display Name: One a Week (Weekly)
  • Description: You will be able to view up to one (1) selfie of a RayWenderlich.com team member each week. This subscription recurs weekly.

Fourth Subscription Values

  • Reference Name: One a Week Monthly
  • Product ID: [Your Bundle ID].sub.oneaweek.monthly
  • Subscription Group Reference Name: Selfies
  • Cleared for Sale: Check the box
  • Duration: 1 Month
  • Free Trial: 1 Week
  • Starting Price: 2.99 USD
  • Localizations: Add English (U.S.)
  • Subscription Display Name: One a Week (Monthly)
  • Description: You will be able to view up to one (1) selfie of a RayWenderlich.com team member each week. This subscription recurs monthly and has a one-week trial period.

Whew, nice work!

Configuring the Subscription Group

Return to the “Selfies” subscription group and add an English (U.S.) localization.

itc-group-localization

  • Subscription Group Display Name: Selfies
  • App Name Display Options: Use App Name

Click Save and then take a cool selfie to commemorate the occasion.

Setting up a Test User

You next need to create a sandbox test user to simulate purchases.

Select My Apps and then pick Users and Roles. Click Sandbox Testers, and then click the + button next to Testers (0).

auto-renewable subscriptions itc-add-test-user

Complete the entire form. Be careful as you enter these values — you can’t recover or edit them later.

Note: You must use a valid e-mail address for this test user.

Within mere moments, you should receive an e-mail from Apple that asks you to verify the test account. You must validate your e-mail, or any purchases you make will silently fail.

Keep the login for this account handy as you’ll need it later in the tutorial.

Obtaining a Shared Secret

The last thing to do in iTunes Connect is obtain a Shared Secret.

Click on My Apps and choose RW Selfies. Navigate to the Features and click View Shared Secret at the top-left side of the “In-App Purchases” table. If necessary, click the button for Generate Shared Secret.

auto-renewable subscriptions itc-shared-secret

Leave this page open because you’ll need it later.

Everything is all set for iTunes Connect! Congratulations for surviving this (not so) horrifically grueling process! 🎉

Implementing StoreKit

It’s finally time to dive into the sample project and write some code! Here’s an overview of the in-app purchase process that you’ll step through:

  1. Prevent free access to content
  2. Load product identifiers
  3. Fetch product information
  4. Present products to the user
  5. Enable users to purchase
  6. Process the transaction
  7. Make purchased content available in the app
  8. Complete the transaction
  9. Restore purchased transactions

Step 1: Prevent Free Access to Content

Before you write the purchase logic, you need to lock down your content. These beautiful faces don’t come for free!

Open SelfiesViewController.swift and replace viewDidLoad with the following:

override func viewDidLoad() {
  super.viewDidLoad()
  guard SubscriptionService.shared.currentSessionId != nil,
    SubscriptionService.shared.hasReceiptData else {
    showRestoreAlert()
    return
  }
  loadSelfies()
}

This block prevents users from loading your precious content without a current session and receipt data. If either is missing, the code triggers an alert that prompts the user to restore purchases.

Note: Apple requires apps to support restoring purchases, so your app must comply. You’ll handle this requirement during step 9.

Steps 2 through 4: Loading, Fetching and Presenting

In this section, you’ll add the logic that allows users to access these incredible selfies.

  1. Load product identifiers
  2. Fetch product information
  3. Present products to the user

For the sake of simplicity, you’ll hardcode the product identifiers — the same ones you set up in iTunes Connect.

When you work with your own app, you might opt to provide these identifiers via a REST call or some other implementation. This would enable you to do things like reveal special purchase options during “holiday sales” or special events.

Open SubscriptionService.swift: this is a singleton service that you’ll use throughout the app to make it easier to work with StoreKit.

Add this import to the top of the file:

import StoreKit

Replace loadSubscriptionOptions with the following and ignore the compiler error for now:

func loadSubscriptionOptions() {
 
  let productIDPrefix = Bundle.main.bundleIdentifier! + ".sub."
 
  let allAccess = productIDPrefix + "allaccess"
  let oneAWeek  = productIDPrefix + "oneaweek"
 
  let allAccessMonthly = productIDPrefix + "allaccess.monthly"
  let oneAWeekMonthly  = productIDPrefix + "oneaweek.monthly"
 
  let productIDs = Set([allAccess, oneAWeek, allAccessMonthly, oneAWeekMonthly])
 
  let request = SKProductsRequest(productIdentifiers: productIDs)
  request.delegate = self
  request.start()
}

You’ve just created an SKProductsRequest by using the product identifiers you defined in iTunes Connect. You also set the delegate to self and started the request.

Now you’ll make SubscriptionService conform to SKProductsRequestDelegate by adding the following extension after the class closing brace:

extension SubscriptionService: SKProductsRequestDelegate {
  func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    options = response.products.map { Subscription(product: $0) }
  }
 
  func request(_ request: SKRequest, didFailWithError error: Error) {
    if request is SKProductsRequest {
      print("Subscription Options Failed Loading: \(error.localizedDescription)")
    }
  }
}

When the SKProductsRequest completes successfully, this extension calls productsRequest(_:didReceive:). It converts the received SKProduct array into a Subscription array that’s set to options. Note that Subscription is a simple model for this app that you’re using instead invoking SKProduct directly.

Should the request fail due to an error, the method calls request(_:didFailWithError:).

Next, you need to call the loadSubscriptionOptions method. Open AppDelegate.swift and replace the following method:

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  SubscriptionService.shared.loadSubscriptionOptions()
  return true
}

Build and run to see your work come to life. Tap the Subscribe Now button shortly after the app launches to see the subscription options.

auto-renewable subscriptions rwselfies-subscription-options

Nice work! You successfully loaded product information from iTunes Connect.

Note: Product identifiers are the only subscription data stored within the app. You should not store pricing or description information in there. iTunes Connect should handle this aspect. Whenever you want to change pricing information, supported regions or localized descriptions, you should make the changes in iTunes Connect.

Step 5: User Makes the Purchase

Now that you’ve got the subscriptions to display, it’d be great to actually let the user purchase one, right? These selfies are worth some serious coin!

Open SubscribeViewController.swift and find the tableView(_:didSelectRowAt:) method at the bottom of the file. Whenever the user selects a row in the table view, you’ll invoke the purchase.

Replace the TODO with the following code:

guard let option = options?[indexPath.row] else { return }
SubscriptionService.shared.purchase(subscription: option)

This gets the selected Subscription instance from options and passes it to purchase(subscription:) on the SubscriptionService.

Pretty straightforward, right? You’re probably itching to see what purchase(subscription:) does. Well, it does absolutely nothing! That’s your job to implement. ;]

Open SubscriptionService.swift and replace purchase(subscription:) with the following:

func purchase(subscription: Subscription) {
  let payment = SKPayment(product: subscription.product)
  SKPaymentQueue.default().add(payment)
}

This creates an SKPayment using the SKProduct associated with the subscription and then adds the payment to the default payment queue. What now? Well, the result of this call is delegated. You’ll need to configure a delegate for the payment queue, which is the next step.

Step 6: Process the Transaction

Open AppDelegate.swift and add this import:

import StoreKit

At the top of application(_:didFinishLaunchingWithOptions:), add the following — just ignore the error for now:

SKPaymentQueue.default().add(self)

This registers the AppDelegate as an SKPaymentTransactionObserver. Add the following after the closing class curly brace to make AppDelegate conform to this protocol:

extension AppDelegate: SKPaymentTransactionObserver {
 
  func paymentQueue(_ queue: SKPaymentQueue,
                    updatedTransactions transactions: [SKPaymentTransaction]) {
 
  }
}

In the above block, you call paymentQueue(_:updatedTrasactions:) whenever something happens with a payment transaction. Making your AppDelegate observe these events is a convenience-driven implementation because it’s a singleton that’s always around when your app is running. Alternatively, you can move this logic to a custom class, but you’ll need to make sure your app will handle these events whenever they’re received.

Fill in the implementation for paymentQueue(_:updatedTransactions:) with the following — again, ignore the errors:

for transaction in transactions {
  switch transaction.transactionState {
  case .purchasing:
    handlePurchasingState(for: transaction, in: queue)
  case .purchased:
    handlePurchasedState(for: transaction, in: queue)
  case .restored:
    handleRestoredState(for: transaction, in: queue)
  case .failed:
    handleFailedState(for: transaction, in: queue)
  case .deferred:
    handleDeferredState(for: transaction, in: queue)
  }
}

This method receives an array of SKPaymentTransaction objects and updates the transactionState, but doesn’t process the transactions.

Each case requires a different response. Add the following right under the above method:

func handlePurchasingState(for transaction: SKPaymentTransaction, in queue: SKPaymentQueue) {
  print("User is attempting to purchase product id: \(transaction.payment.productIdentifier)")
}
 
func handlePurchasedState(for transaction: SKPaymentTransaction, in queue: SKPaymentQueue) {
  print("User purchased product id: \(transaction.payment.productIdentifier)")
}
 
func handleRestoredState(for transaction: SKPaymentTransaction, in queue: SKPaymentQueue) {
  print("Purchase restored for product id: \(transaction.payment.productIdentifier)")
}
 
func handleFailedState(for transaction: SKPaymentTransaction, in queue: SKPaymentQueue) {
  print("Purchase failed for product id: \(transaction.payment.productIdentifier)")
}
 
func handleDeferredState(for transaction: SKPaymentTransaction, in queue: SKPaymentQueue) {
  print("Purchase deferred for product id: \(transaction.payment.productIdentifier)")
}

For now, you’re printing out information for each state.

You can apply some common sense to figure out what each state means by looking at its name, and you can read up on states later. But what about deferred. Huh?

Deferred indicates that a user requested a purchase, but it’s pending until some other user approves it. For example, a child with excellent taste may want this exclusive selfie app but can’t until his mother approves the purchase via the family account.

Steps 7 and 8

In this section, you’ll make the content available and complete the transaction.

Technically, the transaction wasn’t processed in the previous step. Rather, the payment queue’s delegate was informed of an updated transaction. Processing involves a bit more logic, and it’s part of making the content available within the app.

Apple informs you of any successful purchase. From there, it’s your responsibility to determine when and how to deliver the content.

After purchasing an auto-renewable subscription, the user’s receipt data for your app is updated with the subscription information. Receipts reside on the user’s device as cryptographic binary data.

This is all rather complicated and more involved than the scope of this tutorial permits. In essence, the app runs a service that trades receipt data using a Session ID. This Session ID is then used to load the selfies.

Note: The project app runs SelfieService, which accepts receipts and uploads them directly to Apple’s receipt validation service. This is a “cheat” to keep the tutorial focused on setting up the subscriptions. In a real app, you should use a remote server for this — not the app.

The reasoning is that SelfieService could be susceptible to man-in-the-middle attacks. It leaves an opening for a hacker to intercept the request and return a false successful response, thus preventing the request from reaching Apple’s validation service.

You can avoid this issue by having a remote server handle both receipt validation and content vending in a real app. This way, man-in-the-middle attacks aren’t possible. As with all security-related issues, however, you’ll need to consider whether your content is worth the effort required to protect it.

Sam Davies does a stellar job explaining a lot of these details in In-App Purchase Video Tutorial: Part 4 Receipts.

Speaking of SelfieService, there is one thing you need to update there: add your iTunes Connect Shared Secret. Open SelfieService.swift and replace the YOUR_ACCOUNT_SECRET string at the top of the file with the value you generated earlier in iTunes Connect.

Return to AppDelegate to add state handling implementations. Start by replacing handlePurchasedState(for:in:) with the following:

func handlePurchasedState(for transaction: SKPaymentTransaction, in queue: SKPaymentQueue) {
  print("User purchased product id: \(transaction.payment.productIdentifier)")
 
  queue.finishTransaction(transaction)
  SubscriptionService.shared.uploadReceipt { (success) in
    DispatchQueue.main.async {
      NotificationCenter.default.post(name: SubscriptionService.purchaseSuccessfulNotification, object: nil)
    }
  }
}

This method first prints out a message so that you can observe the call in your console, and then it marks the transaction as finished. It’s important to prevent the payment queue from notifying you again about the transaction.

The device’s receipt data is uploaded via SelfieService, and upon completion, a notification is posted.

Open SubscriptionService.swift and locate uploadReceipt(completion:). This method loads receipt data from the device and uploads it to SelfieService. When the operation is successful, SubscriptionService retains the Session ID and the current subscription from the receipt.

You also need to implement loadReceipt():

private func loadReceipt() -> Data? {
  guard let url = Bundle.main.appStoreReceiptURL else {
    return nil
  }
 
  do {
    let data = try Data(contentsOf: url)
    return data
  } catch {
    print("Error loading receipt data: \(error.localizedDescription)")
    return nil
  }
}

The receipt data resides in the App’s main bundle, and fortunately, its URL is easily accessible.

If Bundle.main.appStoreReceiptURL returns a URL, this method attempts to load the data. If the data is available, it’s returned or nil otherwise.

To make purchases via the App Store Sandbox Environment, you’ll need to sign out of your personal App Store account — navigate to Setting\iTunes & App Store, tap your Apple ID at the top and choose Sign Out. Do NOT attempt to sign in here with your Sandox Testing Account.

Build and run.

Tap on Subscribe Now, and choose to purchase One a Week (Weekly). When prompted, tap Use Existing Apple ID and use your sandbox tester account.

rwselfies-buy-oneaweekweekly

Confirm the purchase and press Back and then Subscribed? Come on in…. You should see Andy questioning why you’re spending money on pictures of him.

rwselfies-andy-questions-you

Nice work! You’ve successfully implemented and started testing an in-app purchase of an auto-renewable subscription. Remember that the sandbox accelerates subscription times, so just three minutes after you purchased the subscription you’ll receive the next set of pictures.

The app isn’t configured to automatically refresh the feed, so you’ll need to press Back and then Subscribed? Come on in… again to see the next batch of selfies.

While you’re waiting, prepare to upgrade your subscription when you re-enter the app to All Access (Weekly).

A caveat of the sandbox environment is that it will only auto-renew subscriptions for the same sandbox user six times per day. After this, you can still make purchases, but they won’t automatically renew.

SelfiesService also has some built-in nuances to make testing easier. Upon app startup, it saves the current time and stores it in UserDefaults. Subscriptions purchased prior to this time are ignored, so you can delete, re-install the app and make purchases again. You wouldn’t want a real app to do this in production.

Step 9: Restore Purchased Transactions

Lastly, you’ll need to provide users with a means to restore purchases. Users delete apps, lose and upgrade devices all the time. “RW team selfies are so compelling, I’d gladly pay for them again”, says no user…ever. So, you need to allow users to access content they’ve previously purchased.

The sample app’s configuration allows the user to restore purchases if SelfiesViewController found no receipt when it loaded.

Open SubscriptionService.swift and replace restorePurchases() with the following:

func restorePurchases() {
  SKPaymentQueue.default().restoreCompletedTransactions()
}

This tells StoreKit to restore all transactions that you previously marked as finished.

You need to update AppDelegate too, since it’s the payment queue’s delegate. Open AppDelegate.swift and add the following to the end of handleRestoredState(for:in:) after the print statement:

queue.finishTransaction(transaction)
SubscriptionService.shared.uploadReceipt { (success) in
  DispatchQueue.main.async {
    NotificationCenter.default.post(name: SubscriptionService.restoreSuccessfulNotification, object: nil)
  }
}

This again marks the transaction as processed, uploads the receipt data, and posts the relevant notification to unlock the content.

Whew, that’s a lot of bookkeeping. Get it? Money, sales… Oh fine…!

Where To Go From Here?

Here’s the final app in case you’d like to see the finished project. Note that you’ll still need to set your own development team, do all of the iTunes Connect set up and set your iTunes Connection shared secret to use the completed app.

Now that you have an idea of what’s required to set up auto-renewable subscriptions, there are a few things you should review further before adding them to your own apps:

I hope you enjoyed this tutorial. Please use the forum below for any questions or comments!

The post In-App Purchases: Auto-Renewable Subscriptions Tutorial appeared first on Ray Wenderlich.

RWDevCon 2017 Vault Now Available!

$
0
0

RWDevCon 2017 Vault Bundle

A few weeks ago, we ran our third annual tutorial conference, RWDevCon 2017, which was our best conference yet.

Attendees called the conference “more amazing than I could ever have imagined”, “the best technical conference of the year”, and my personal favorite: “way better than WWDC!” :]

For the third year in a row, RWDevCon has sold out. But if you weren’t able to get a ticket, don’t worry – you can still be part of the fun!

Join over 500 people who will be enjoying the RWDevCon experience virtually – through the RWDevCon 2017 Vault Bundle!

And best yet – it’s fully available today.

Keep reading to find out what the RWDevCon 2017 Vault Bundle is, how to get the launch discount, and how to enter for a chance to win a free copy.

What is the RWDevCon 2017 Vault Bundle?

The RWDevCon 2017 Vault Bundle consists of four things:

  • 2 advanced workshops
  • 24 hands-on tutorials
  • 1.3GB+ of sample projects
  • 600+ pages of conference books

Let’s look at each in more detail.

1) Two Advanced Workshops

The first thing the RWDevCon 2017 Vault Bundle includes is the two advanced workshops we had at the conference: in video form!

The first workshop is Advanced Debugging & Reverse Engineering.

Advanced Apple Debugging and Reverse Engineering Workshop

In this workshop, Derek Selander teaches you how to wield the power of LLDB and other debugging tools and dig deep into code.

Not only will you learn to find bugs faster, but you’ll also learn how other developers have solved problems similar to yours. At the end of this workshop, you’ll have the tools and knowledge to answer even the most obscure question about your code — or someone else’s.

Here’s what some of the attendees had to say about the Advanced Debugging & Reverse Engineering workshop:

  • “One of the best talks/tutorials I’ve ever participated in. We blew past years of my debugging experience in the first hour. Derek was able to make assembly debugging approachable.”
  • “The speaker was very exciting & enthusiastic about the materials. I felt very exciting as a result & encouraged/inspired to use LLDB for debugging.”
  • “My mind was blown several times!”

The second workshop is Advanced App Architecture.

Advanced App Architecture Workshop

Thoughtful design of the boundaries between your apps subsystems is the foundation of a stable codebase.

In this workshop, René Cacheaux and Josh Berlin teach you how to create a well designed boundary between subsystems, dependency injection, use case driven development, creating injectable subsystems, and using state management to result in a clean architecture for your apps.

Here’s what some of the attendees had to say about the Advanced App Architecture workshop:

  • “The material was really cool. You guys finally explained dependency injection in a way I understood.”
  • “The workshop was great! Good example app, and I liked the real life content.”
  • “Great knowledge, preparation, and topics!”

2) 24 Hands-On Tutorials

The second thing the RWDevCon 2017 Vault Bundle includes is all 24 tutorial sessions from the conference: in video form.

Here’s a rundown of what’s covered:

  1. Advanced Core Data: Core Data has many advanced features which can make development of complex apps easier while increasing performance. You’ll learn how to take advantage of some of the advanced features of Core Data such as background fetching and child contexts.
  2. Advanced Auto Layout: Learn how you can use some of Auto Layout’s more advanced features to your advantage while designing complex, dynamic views.
  3. Machine Learning on iOS: Machine Learning. Convolutional Neural Networks. Deep Learning Neural Networks. What is all the hype about? What are these technologies, what are they good for, and can we use them for anything useful right now? This session requires no background in any of these areas, and will introduce you to machine learning on iOS with a worked example.
  4. iOS Concurrency: Learn how to add concurrency to your apps with GCD & Operations. Keep your app’s UI responsive to give your users a great user experience, and learn how to avoid common concurrency problems, like race condition and deadlock.
  5. Reconstructing Popular iOS Animations: In this session, you’ll examine two high profile apps with gorgeous fluid, tactile interfaces and reconstruct them yourself.
  6. Mastering Git: In this session you’ll learn some of Git’s more advanced topics, such as rebasing, hooks and history mutation. You’ll also gain a better understanding of how Git works under the covers and gain some experience with realistic day-to-day scenarios.
  7. Learn how to truly use Git the way it was designed to be used!

  8. Building Reusable Frameworks: Using shared code from the community has become a major benefit for developers. Why not pay it back and share the awesome things you’ve written with the world? In this session, you’ll learn how to create a framework from your code that’s compatible with all three of the main dependency manager players: Cocoapods, Carthage, and the Swift Package Manager.
  9. Swift Memory Management: While the design of Swift and the compiler relieve you from much of the drudgery associated with reference counting, it’s critical that you understand what the system is doing for you, so that you can create higher performance, bug-free apps. Learn how to think about objects and closures and how to use the latest Xcode tools to analyze and debug your code.
  10. Cross-Platform React Native: React Native is a framework for building native apps with React. It’s been used by many developers who are drawn to it’s learn once, write anywhere paradigm and fast development cycle. In this session you’ll learn how to create a cross-platform (iOS and Android) app, learning how to create an app from scratch and how to integrate React Native into an existing native app.
  11. Fastlane: Fastlane is a suite of tools to help automate building and release iOS (and Android!) apps. From creating screenshots to handling provisioning to submitting your application, Fastlane can help with it all. In this session, you’ll learn how to use these tools to help automate the mundane tasks you dread doing in iTunes Connect.
  12. RxSwift in Practice: RxSwift, and its companion framework RxCocoa, allow you to create reactive apps for iOS and macOS. Your first look at Rx code might be intimidating without a proper introduction, but in this session you will start in Playgrounds, learn the core concepts, and then move on to building a real iOS application in Xcode. Just beware – you might like programming with RxSwift too much!
  13. How to Make a Platformer Game in Unity: Unity is used by thousands of indie development studios, hobbyist game developers, and even AAA game studios. In this session you’ll power through creating a platformer game like Super Meat Boy, and learn firsthand how easy it is to be productive with this powerful and versatile multi-platform game engine.
  14. iMessage Apps: The Messages framework in iOS 10 allows developers to extend their apps to iMessages to further their app’s reach. In this session, you’ll learn how to extend an existing app by adding a Messages extension.
  15. Learn to create your own iMessage apps!

  16. Practical Unit Testing I: Unit tests allow you to develop without fear and ship with confidence. They can even serve as documentation for your code and make everything easier to understand. But you already know this, don’t you? In this session you will explore ways to add at least one more unit test to your app.
  17. Server Side Swift with Perfect: Perfect is an open source server side Swift framework that allows you to create web apps, or web APIs, purely in Swift. In this session, you’ll learn how to create your first web app in Swift from scratch, including templating, persistence, and authentication.
  18. Swift Playgrounds in Depth: Swift playgrounds have come a long way since their initial release in 2014 alongside the Swift language. This session covers a broad range of topics, a few of which are interactive playgrounds, how to use external frameworks, prototyping animations and much more. Along the way you’ll also learn a few practical tips and tricks to take your playground-fu to the next level.
  19. Practical Unit Testing II: Continuous Integration (CI) is the art of automatically translating your code into a build that can be easily accessed by project stakeholders. In the first half of this session, you’ll work through different aspects of CI setup design, followed by a review of fundamentals that can be applied to any CI solution. In the second half, you’ll look at a demo CI setup for the project created in Practical Unit Testing I.
  20. Cocoa Bindings: In this session, you’ll cover the basic of bindings, how to set them up in Interface Builder, some common debugging pitfalls, and some binding related tools, such as value transformers and number formatters.
  21. Engaging On-Boarding: Users abandon apps when they can’t figure out how to use it fast enough. To lower the abandonment rate for your app, create an on-boarding experience that keeps the user engaged, informed and delighted the first time they open your app. In this session, you’ll look at the pros and cons on on-boarding, when to use it, and best practices. Finally, you will brainstorm and implement your own on-boarding experience!
  22. Learn what makes for engaging and interesting on-boarding in your apps.

  23. Advanced iOS Design Patterns: In this talk, you’ll learn some design patterns for solving common iOS development problems, including: authentication and auto re-login; networking and domain model management; and data persistence and cache management.
  24. Android for iOS Developers: It seems almost everything is cross-platform these days. Learn how to make a simple, professional Android app using Material Design, Realm, and Retrofit 2.
  25. Deploying Server-Side Swift Apps with Docker: Docker makes it easier to create, deploy, and run applications by using containers. You’ll learn how to package up your server-side Swift app as a custom Docker image, and leverage Docker Compose to take that image and create a container that can be used for both local development and in production. You’ll also learn about multiple containers, and how to set up dependencies between them.
  26. Swift Error Handling: The best apps delight their users by remaining responsive and stable in the face of errors. In this session, you’ll learn how to write code that responds to and recovers from errors, and even anticipates them.
  27. Game AI with GameplayKit: GameplayKit is an independent Apple framework that game developers may use to help them create better games, with less effort. In this session, you’ll learn how to use GameplayKit to add artificial intelligence (AI) to your games.

Wow – that’s a lot of tutorials! Here’s what our attendees had to say about them:

  • “The demos and labs are invaluable! Excellent practice. Would come back in the future, and would recommend to a friend (and have already).”
  • “I’ve been to many conferences, and RWDevCon is so much unlike all of them. It was awesome getting hands-on experience with interesting concepts. Very well run.”
  • “Most informative conference I’ve been to. I attended some seriously great tutorials/workshops with some amazing instructors.”

3) 1.3GB+ of Sample Projects

The third thing the RWDevCon 2017 Vault Bundle includes is 1.3GB+ of all of the sample projects from the conference!

Each tutorial is split into three parts:

  • Hands-On Demo 1 with a starter and final project
  • Hands-On Demo 2 with a starter and final project
  • Hands-On Lab with a starter and final project

These are all great practice, and you’ll have tons of working sample code to use in your own apps.

4) 600+ Pages of Conference Books

The final thing the RWDevCon 2017 Vault Bundle includes is the official conference books, which include 600+ pages of material!

There’s one book for the tutorials, and one for the workshops. The books include step-by-step instructions for each demo, and a full guided tutorial for each lab.

RWDevCon 2017 Vault Week and Giveaway

To celebrate the launch of the RWDevCon 2017 Vault, each day this week we’re going to do something special:

  • Today the RWDevCon 2017 Vaults are released!
  • On Tuesday-Thursday we’ll release 3 tutorials from the conference for free. This will give you a chance to check them out and see if you like them – we’re confident you will! :]
  • On Friday we’ll round out our week of celebration with a special giveaway. 3 lucky winners will win a copy of the RWDevCon 2017 Vault Bundle (or a book of your choice if you already have the RWDevCon 2017 Vault Bundle).

To enter into this giveaway, simply leave a comment on this post. We’ll choose winners randomly and announce the results on Friday.

Where To Go From Here?

For this week only, the RWDevCon 2017 Vault is available at a massive 50% off discount!

  • If you preordered the RWDevCon 2017 Vault, you should have access now: just visit the Tutorial Vault or the Workshop Vault.
  • If you attended RWDevCon 2017, you’ll get free access to the appropriate Vault, based on your ticket type. You should have access based on the email we have on file from the conference, but if you can’t access the videos please contact us and we’ll get it sorted out.
  • If you don’t have the RWDevCon 2017 Vault yet, what are you waiting for? There’s a ton of amazingly useful content in the Vault, and you don’t want to miss your chance for the 50% off discount, which ends Friday April 28.

The RWDevCon team and I hope you enjoy the RWDevCon 2017 Vault, and we hope you enjoy all the hands-on tutorials!

The post RWDevCon 2017 Vault Now Available! appeared first on Ray Wenderlich.

Video Tutorial: Practical Instruments Part 1: Introduction

Video Tutorial: Practical Instruments Part 2: Instruments 101

New Course: Practical Instruments

$
0
0

Earlier this year, we surveyed raywenderlich.com subscribers to see what courses they wanted next. One of the top picks was a course on Xcode Instruments.

Here’s what some folks we surveyed had to say:

  • “I have been developing for iOS for 4 years already and remember to have used Instruments just a few times. It was all due to the fact that it is extremely hard for me to interpret the data Instruments produce.”
  • “I have been coding iOS for a number of years now, but I have never really gotten the hang of instruments, which really annoys me. I may be slow, but I find the task of figuring out where all my CPU and memory resources are used, a surprisingly difficult task in instruments.”
  • “As a professional developer, I can’t believe how much I DON’T use instruments. I think it’s mostly because I don’t feel comfortable with it.”

It’s clear there’s a lot of confusion about Instruments, and as a huge Instruments fan I was really eager to share how useful and great it can be.

So for the past few months I’ve been working on a new course on the topic, and I’m thrilled to announce it’s available today: Practical Instruments!

In this 8-part course, you’ll learn how to use Instruments to improve your code. You’ll get familiar with the interface, and find out which Instruments to use to solve your performance, memory, and battery problems in real-world scenarios.

This course is fully up-to-date with Swift 3, Xcode 8, and iOS 10. Let’s take a look at what’s inside:

Video 1: Introduction. In this video, you’ll get an introduction to the course and an overview of all the problems you can solve with Instruments.

Video 2: Instruments 101. This time you’ll get acquainted with Time Profiler and learn about the various panes and settings of an Instruments trace.

Video 3: Time Profiler. Learn how to profile your app’s performance as well as some strategies for speeding things up.

Video 4: Optimizing Launch. This time, you’ll zoom in on profiling and improving the launch time of your app.

Video 5: Memory. Learn how to track down and fix memory leaks using the Debug Memory Graph and the Leaks Template.

Video 6: Core Animation. Get a look at how you can profile and improve the performance of your app’s UI and how to find slowdowns that won’t show up in Time Profiler.

Video 7: Energy. Learn what kinds of things can affect your app’s energy usage as well as some strategies for tracking down and fixing problems.

Video 8: Conclusion. In this video you’ll get a recap of what you’ve learned so far and a few pointers for further study.

Where To Go From Here?

Want to check out the course? You can watch the introduction for free!

The rest of the course is for raywenderlich.com subscribers only. Here’s how you can get access:

  • If you are a raywenderlich.com subscriber: You can access the first two parts of Practical Instruments today, and the rest will be coming out over the next two weeks.
  • If you are not a subscriber yet: What are you waiting for? Subscribe now to get access to our new Practical Instruments course and our entire catalog of over 500 videos.

There’s much more in store for raywenderlich.com subscribers – if you’re curious, you can check out our full schedule of upcoming courses.

I hope you enjoy our new course, and stay tuned for many more new Swift 3 courses and updates to come!

The post New Course: Practical Instruments appeared first on Ray Wenderlich.

Last Year’s RWDevCon 2016 Vault Now Free!

$
0
0

Yesterday, we released the RWDevCon 2017 Vault Bundle, a collection of 2 advanced workshops, 24 hours of hands-on tutorials, 1.3GB+ of sample projects, and 600+ pages of conference books.

To celebrate the release of the this year’s Vault, we have some good news: we are releasing last year’s Vault (the 2016 Vault) for free!

Last year’s RWDevCon 2016 Vault contains all of the videos and materials from our 2016 conference. If you haven’t seen the 2016 Vault yet, there are some gems in there you’ll definitely want to check out:

Note that last year’s materials were made for iOS 9 and Swift 2, but if you are an experienced developer you should have no problem updating them for Swift 3.

We hope you enjoy last year’s Vault – and if you like what you see, consider picking up this year’s RWDevCon 2017 Vault Bundle as well. Enjoy!

The post Last Year’s RWDevCon 2016 Vault Now Free! appeared first on Ray Wenderlich.


UIAppearance Tutorial: Getting Started

$
0
0
Update: Updated for Xcode 8 and Swift 3 by Ron Kliffer. Original tutorial by Essan Parto.

UIAppearance Tutorial: Getting Started

Although skeuomorphism in iOS apps is a thing of the past, that doesn’t mean you’re limited to the stock appearance of controls in your iOS app.

True, you can develop your own controls and app stylings from scratch, but Apple recommends you use standard UIKit controls, and take advantage of the various customization techniques in iOS. This is because UIKit controls are highly efficient, and your customizations to the controls should be mostly future-proof.

In this UIAppearance tutorial, you’ll use some basic UI customization techniques to customize a plain Pet Finder app and make it stand out from the pack! :]
As an added bonus, you’ll learn how to automatically switch your app to a dark theme when opened at night.

Getting Started

Download the starter project for this tutorial here. The app has many of the standard UIKit controls and looks extremely vanilla.

Open the project and have a look around to get a feel for its structure. Build and run the app, you’ll see the main UI elements of Pet Finder:

uiappearance

There’s a navigation bar and a tab bar. The main screen shows a list of pets. Tap a pet to see some details about it. There’s a search screen as well and — aha! A screen that allows you to select a theme for your app. That sounds like a pretty good place to start!

UIAppearance: Supporting Themes

Many apps don’t allow users to select a theme, and it’s not always advisable to ship an app with a theme selector. However, there are cases where themes could be very useful. You might want to test different themes during development to see which ones work best for your app. You might A/B test your app with your beta users to see which style is the most popular. Or you might want to ease your user’s eyes by adding a dark theme for night times.

In this UIAppearance tutorial, you’ll create a number of themes for your app that you can try out to see which one is most aesthetically pleasing.

Select File\New\File… and choose iOS\Source\Swift File. Click Next and type Theme as the name of the file. Finally click Create.

Replace the contents of the file with the following:

import UIKit

enum Theme: Int {
  //1
  case `default`, dark, graphical

  //2
  private enum Keys {
    static let selectedTheme = "SelectedTheme"
  }

  //3
  static var current: Theme {
    let storedTheme = UserDefaults.standard.integer(forKey: Keys.selectedTheme)
    return Theme(rawValue: storedTheme) ?? .default
  }
}

Let’s see what this code does:

  1. Defines three types of themes – default, dark and graphical
  2. Defines a constant to help you access the selected theme
  3. Defines a read-only computed type property for the selected theme. It uses UserDefaults to persist the current theme, and returns the default theme if none were previously selected.

Now you have your Theme enum set up, let’s add some style to it. Add the following code to the end of Theme before the closing brace:

var mainColor: UIColor {
  switch self {
  case .default:
    return UIColor(red: 87.0/255.0, green: 188.0/255.0, blue: 95.0/255.0, alpha: 1.0)
  case .dark:
    return UIColor(red: 255.0/255.0, green: 115.0/255.0, blue: 50.0/255.0, alpha: 1.0)
  case .graphical:
    return UIColor(red: 10.0/255.0, green: 10.0/255.0, blue: 10.0/255.0, alpha: 1.0)
  }
}

This defines a mainColor that’s specific to each particular theme.

Let’s see how this works. Open AppDelegate.swift and add the following line to application(_:didFinishLaunchingWithOptions:):

print(Theme.current.mainColor)

Build and run the app. You should the following printed to the console:

UIExtendedSRGBColorSpace 0.341176 0.737255 0.372549 1

At this point, you have three themes and can manage them through Theme. Now it’s time to go use them in your app.

Applying Themes to Your Controls

Open Theme.swift, add the following method to the bottom of Theme:

func apply() {
  //1
  UserDefaults.standard.set(rawValue, forKey: Keys.selectedTheme)
  UserDefaults.standard.synchronize()

  //2
  UIApplication.shared.delegate?.window??.tintColor = mainColor
}

Here’s a quick run-through of the above code:

  1. Persist the selected theme using UserDefaults.
  2. Apply the main color to the tintColor property of your application’s window. You’ll learn more about tintColor in just a moment.

Now the only thing you need to do is call this method.

Open AppDelegate.swift and replace the print() statement you added earlier with the following:

Theme.current.apply()

Build and run the app. You’ll see your new app looks decidedly more green:

uiappearance

Navigate through the app. There’s green accents everywhere! But you didn’t change any of your controllers or views. What is this black — er, green — magic?! :]

Applying Tint Colors

Since iOS 7, UIView has exposed the tintColor property. This is often used to define the primary color for interface elements throughout an app.

When you specify a tint for a view, it’s automatically propagated to all subviews in that view’s view hierarchy. Since UIWindow inherits from UIView, you can specify a tint color for the entire app by setting the window’s tintColor. That’s exactly what you did in apply() above.

Click on the Gear icon in the top left corner of your app. A table view with a segmented control slides up. When you select a different theme and tap Apply, nothing changes. Time to fix that.

Open SettingsTableViewController.swift and add these lines to applyTheme(_:), just above dismissAnimated():

if let selectedTheme = Theme(rawValue: themeSelector.selectedSegmentIndex) {
  selectedTheme.apply()
}

Here you call the method you added to Theme, which sets the selected theme’s mainColor on the root UIWindow.

Next, add the following line to the bottom of viewDidLoad(). This will select the theme persisted to UserDefaults when the view controller is first loaded:

themeSelector.selectedSegmentIndex = Theme.current.rawValue

Build and run the app. Tap the settings button, select Dark, and then tap Apply. The tint in your app will change from green to orange right before your eyes:

uiappearance

Eagle-eyed readers likely noticed these colors were defined in mainColor, in Theme.

But wait, you selected Dark, and this doesn’t look dark. To get this effect working, you’ll have to customize a few more things.

Customizing the Navigation Bar

Open Theme.swift and add the following two properties to Theme:

var barStyle: UIBarStyle {
  switch self {
  case .default, .graphical:
    return .default
  case .dark:
    return .black
  }
}

var navigationBackgroundImage: UIImage? {
  return self == .graphical ? UIImage(named: "navBackground") : nil
}

These methods simply return an appropriate bar style and background image for the navigation bar for each theme.

Next, add the following lines to the bottom of apply():

UINavigationBar.appearance().barStyle = barStyle
UINavigationBar.appearance().setBackgroundImage(navigationBackgroundImage, for: .default)

Okay — why does this work here? Shouldn’t you be accessing a UINavigationBar instance?

UIKit has an informal protocol called UIAppearance that most of its controls conform to. When you call appearance() on UIKit classes— not instances —it returns a UIAppearance proxy. When you change the properties of this proxy, all the instances of that class automatically get the same value. This is very convenient as you don’t have to manually style each control after it’s been instantiated.

Build and run the app. Select the Dark theme and the navigation bar should now be much darker:

uiappearance

This looks a little better, but you still have some work to do.

Next, you’ll customize the back indicator. iOS uses a chevron by default, but you can code up something far more exciting! :]

Customizing the Navigation Bar Back Indicator

This change applies to all themes, so you only need to add the following lines to apply() in Themes.swift:

UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backArrow")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "backArrowMask")

Here you’re simply setting the image and transition mask image to be used as the back indicator.

Build and run the app. Tap one of the pets and you should see the new back indicator:

uiappearance

Open Images.xcassets and find the backArrow image in the Navigation group. The image is all black, but in your app it takes on the tint color of your window and it just works.

uiappearance

But how can iOS just change the bar button item’s image color, and why doesn’t it do that everywhere?

As it turns out, images in iOS have three rendering modes:

  • Original: Always use the image “as is” with its original colors.
  • Template: Ignore the colors, and use the image as a stencil. In this mode, iOS uses only the shape of the image, and colors the image itself before rendering it on screen. So when a control has a tint color, iOS takes the shape from the image you provide and uses the tint color to color it.
  • Automatic: Depending on the context in which you use the image, the system decides whether it should draw the image as “original” or “template”. For items such as back indicators, navigation control bar button items and tab bar images, iOS ignores the image colors by default. You can override this behavior and change the rendering mode manually.

Head back to the app, tap one of the pets and tap Adopt. Watch the animation of the back indicator in the navigation bar carefully. Can you see the problem?

uiappearance

When the Back text transitions to the left, it overlaps the indicator and looks pretty bad:

To fix this, you’ll have to change the transition mask image.

Update the line where you set backIndicatorTransitionMaskImage in apply(), in Theme.swift, to the following:

UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "backArrow")

Build and run the app. Once again tap one of the pets and then tap Adopt. This time the transition looks much better:

uiappearance

The text is no longer cut off and looks like it goes underneath the indicator. So, what’s happening here?

iOS uses all the non-transparent pixels of the back indicator image to draw the indicator. However, it does something entirely different with the transition mask image. It masks the indicator with the non-transparent pixels of the transition mask image. So when the text moves to the left, the indicator is only visible in the those areas.

In the original implementation, you provided an image that covered the entire surface of the back indicator. That’s why the text remained visible through the transition. Now you’re using the indicator image itself as the mask, it looks better. But if you look carefully, you’ll see the text disappeared at the far right edge of the mask, not under the indicator proper.

Look at the indicator image and the “fixed” version of the mask in your image assets catalog. You’ll see they line up perfectly with each other:

uiappearance

The black shape is your back indicator and the red shape is your mask. You want the text to only be visible when it’s passing under the red area and hidden everywhere else.

To do this, change the last line of apply() once again, this time to use the updated mask:

UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "backArrowMaskFixed")

Build and run the app. For the last time, tap one of the pets and then tap Adopt. You’ll see the text now disappears under the image, just as you anticipated it would:

uiappearance

Now your navigation bar is pixel perfect, it’s time to give the tab bar some much-needed love.

Customizing the Tab Bar

Still in Theme.swift, add the following property to Theme:

var tabBarBackgroundImage: UIImage? {
  return self == .graphical ? UIImage(named: "tabBarBackground") : nil
}

This property will provide appropriate tab bar background images for each theme.

To apply these styles, add the following lines to apply().

UITabBar.appearance().barStyle = barStyle
UITabBar.appearance().backgroundImage = tabBarBackgroundImage

let tabIndicator = UIImage(named: "tabBarSelectionIndicator")?.withRenderingMode(.alwaysTemplate)
let tabResizableIndicator = tabIndicator?.resizableImage(
  withCapInsets: UIEdgeInsets(top: 0, left: 2.0, bottom: 0, right: 2.0))
UITabBar.appearance().selectionIndicatorImage = tabResizableIndicator

Setting the barStyle and backgroundImage should be familiar by now. It’s done exactly the same way you did for UINavigationBar previously.

In the final three lines of code above, you retrieve an indicator image from the asset catalog and set its rendering mode to .AlwaysTemplate. This is an example of one context where iOS doesn’t automatically use template rendering mode.

Finally, you create a resizable image and set it as the tab bar’s selectionIndicatorImage.

Build and run the app. You’ll see your newly themed tab bar:

uiappearance

The dark theme is starting to look more, well, dark! :]

See the line below the selected tab? That’s your indicator image. Although it’s only 6 points high and 49 points wide, iOS stretches this to the full width of the tab at run time.

The next section covers resizeable images and how they work.

Customizing a Segmented Control

One element that hasn’t changed yet is the segmented control that shows the currently selected theme. Time to bring that control into the wonderful world of theming.

Add the following code to the bottom of apply() in Theme.swift:

let controlBackground = UIImage(named: "controlBackground")?
  .withRenderingMode(.alwaysTemplate)
  .resizableImage(withCapInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3))

let controlSelectedBackground = UIImage(named: "controlSelectedBackground")?
  .withRenderingMode(.alwaysTemplate)
  .resizableImage(withCapInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3))

UISegmentedControl.appearance().setBackgroundImage(controlBackground,
                                                   for: .normal,
                                                   barMetrics: .default)
UISegmentedControl.appearance().setBackgroundImage(controlSelectedBackground,
                                                   for: .selected,
                                                   barMetrics: .default)

To understand the code above, first take a look at the controlBackground image in your asset catalog. The image may be tiny, but iOS knows exactly how to use it to draw the borders of your UISegmentedControl, as it’s been pre-sliced and is resizable.

What does sliced mean? Take a look at the following magnified model:

uiappearance

There are four 3×3 squares, one in each corner. These squares are left untouched when resizing the image. The gray pixels however, get stretched horizontally and vertically as required.

In your image, all the pixels are black and assume the tint color of the control. You instruct iOS how to stretch the image using UIEdgeInsets(). You pass 3 for the top, left, bottom and right parameters since your corners are 3×3.

Build and run the app. Tap the Gear icon in the top left and you’ll see the UISegmentedControl now reflects your new styling:

uiappearance

The rounded corners are gone and have been replaced by your 3×3 square corners.

Now you’ve tinted and styled your segmented control, all that’s left is to tint the remaining controls.

Close the settings screen in the app, and tap the magnifier in the top right corner. You’ll see another segmented control, along with a UIStepper, UISlider, and UISwitch still need to be themed.

Grab your brush and drop cloths — you’re going painting! :]

Customizing Steppers, Sliders, and Switches

To change the colors of the stepper, add the following lines to apply() in Theme.swift:

UIStepper.appearance().setBackgroundImage(controlBackground, for: .normal)
UIStepper.appearance().setBackgroundImage(controlBackground, for: .disabled)
UIStepper.appearance().setBackgroundImage(controlBackground, for: .highlighted)
UIStepper.appearance().setDecrementImage(UIImage(named: "fewerPaws"), for: .normal)
UIStepper.appearance().setIncrementImage(UIImage(named: "morePaws"), for: .normal)

You’ve used the same resizable image as you did for UISegmentedControl. The only difference here is UIStepper segments become disabled when they reach their minimum or maximum values, so you also specified an image for this case as well. To keep things simple, you re-use the same image.

This not only changes the color of the stepper, but you also get some nice image buttons instead of the boring + and symbols.

Build and run the app. Open Search to see how the stepper has changed:

uiappearance

UISlider and UISwitch need some theme lovin’ too.

Add the following code to apply():

UISlider.appearance().setThumbImage(UIImage(named: "sliderThumb"), for: .normal)
UISlider.appearance().setMaximumTrackImage(UIImage(named: "maximumTrack")?
  .resizableImage(withCapInsets:UIEdgeInsets(top: 0, left: 0.0, bottom: 0, right: 6.0)), for: .normal)

UISlider.appearance().setMinimumTrackImage(UIImage(named: "minimumTrack")?
  .withRenderingMode(.alwaysTemplate)
  .resizableImage(withCapInsets:UIEdgeInsets(top: 0, left: 6.0, bottom: 0, right: 0)), for: .normal)

UISwitch.appearance().onTintColor = mainColor.withAlphaComponent(0.3)
UISwitch.appearance().thumbTintColor = mainColor

UISlider has three main customization points: the slider’s thumb, the minimum track and the maximum track.

The thumb uses an image from your assets catalog. The maximum track uses a resizable image in original rendering mode so it stays black regardless of the theme. The minimum track also uses a resizable image, but you use template rendering mode so it inherits the tint of the template.

You’ve modified UISwitch by setting thumbTintColor to the main color. You set onTintColor as a slightly lighter version of the main color, to bump up the contrast between the two.

Build and run the app. Tap Search and your slider and switch should appear as follows:

uiappearance

Your app has become really stylish, but dark theme is still missing something. The table background is too bright. Let’s fix that.

Customizing UITableViewCell

In Theme.swift, add the following properties to Theme:

var backgroundColor: UIColor {
  switch self {
  case .default, .graphical:
    return UIColor.white
  case .dark:
    return UIColor(white: 0.4, alpha: 1.0)
  }
}

var textColor: UIColor {
  switch self {
  case .default, .graphical:
    return UIColor.black
  case .dark:
    return UIColor.white
  }
}

These define the background color you’ll use for your table cells, and the text color for the labels in it.

Next, add the following code to the end of apply():

UITableViewCell.appearance().backgroundColor = backgroundColor
UILabel.appearance(whenContainedInInstancesOf: [UITableViewCell.self]).textColor = textColor

The first line should look familiar, it simply sets the backgroundColor of all UITableViewCell instances. The second line however is where things get a little more interesting.
UIAppearance let’s you condition the changes you want to make. In this case, you don’t want to change the entire app’s text color. You only want to change the text color inside UITableViewCell. By using whenContainedInInstancesOf: you do exactly that. You force this change to apply only to UILabel instances inside a UITableViewCell.

Build and run the app, choose dark theme, and the screen should look like this:
uiappearance

Now this is a real dark theme!

As you’ve seen by now, the appearance proxy customizes multiple instances of a class. But sometimes you don’t want a global appearance for a control. In these cases, you can customize just a single instance of a control.

Customizing a Single Instance

Open SearchTableViewController.swift and add the following lines to viewDidLoad():

speciesSelector.setImage(UIImage(named: "dog"), forSegmentAt: 0)
speciesSelector.setImage(UIImage(named: "cat"), forSegmentAt: 1)

Here you’re simply setting the image for each segment in the species selector.

Build and run the app. Open Search and you’ll see the segmented species selector looks like this:

uiappearance

iOS inverted the colors on the selected segment’s image without any work on your part. This is because the images are automatically rendered in Template mode.

What about selectively changing the typeface on your controls? That’s easy as well.

Open PetViewController.swift and add the following line to the bottom of viewDidLoad():

view.backgroundColor = Theme.current.backgroundColor

Build and run the app. Select a pet, and look at the result:
uiappearance

You’re done with the styling. The image below shows the before and after results of the Search screen:
uiappearance

I think you’ll agree the new version is much less vanilla and much more interesting than the original. You’ve added 3 dazling styles and spiced up the app.

But why don’t you take it a step further? What if you helped the user by opening the app with the appropriate theme according to when he opened it? What if you switched to dark theme as the sun sets? Let’s see how we can make that happen.

Automating dark theme with Solar

For this part of the tutorial, you’ll use an open source library called Solar. Solar receives a location and date, and returns the sunrise and sunset times for that day. Solar comes installed with the starter project for this tutorial.

Note: For more on Solar, visit the library’s GitHub repository

Open AppDelegate.swift and add the following property below var window:

private let solar = Solar(latitude: 40.758899, longitude: -73.9873197)!

This defines a property of type Solar with today’s date and a given location. You can of course change the location so it’ll be taken dynamically according to the user’s location.

Still in AppDelegate, add the following two methods:

//1
func initializeTheme() {
  //2
  if solar.isDaytime {
    Theme.current.apply()
    scheduleThemeTimer()
  } else {
    Theme.dark.apply()
  }
}

func scheduleThemeTimer() {
  //3
  let timer = Timer(fire: solar.sunset!, interval: 0, repeats: false) { [weak self] _ in
    Theme.dark.apply()

    //4
    self?.window?.subviews.forEach({ (view: UIView) in
      view.removeFromSuperview()
      self?.window?.addSubview(view)
    })
  }

  //5
  RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}

Let’s see what’s going on here:

  1. You define a method to initialize theme settings
  2. Solar has a convenience method to check if the time it was given is in daytime. If so, you apply the current theme and schedule a Timer that will change themes.
  3. You create a timer and set it to fire at sunset.
  4. This is an important thing to notice. Whenever UIAppearance changes values, they will not be reflected until the view re-renders itself. By removing and re-adding all the views to their window, you assure they are re-rendered according to the new theme.
  5. You schedule the timer by adding it to the main RunLoop

Finally, in application(_:didFinishLaunchingWithOptions:), replace:

Theme.current.apply()

with:

initializeTheme()

Open the app after sunset (You can change the time on your phone if you’re reading this during the day). The app should appear with dark theme selected.

Where to Go From Here?

You can download the finished project with all the tweaks from this tutorial here.

In addition to the tweaks you’ve already made, UIAppearance also supports customizing controls for a specific UITraitConnection. This let’s you support multiple themes for different device layouts.

I hope you enjoyed this UIAppearance tutorial and learned how easy it can be to tweak your UI. If you have any comments or questions about this tutorial, please join the forum discussion below!

The post UIAppearance Tutorial: Getting Started appeared first on Ray Wenderlich.

RWDevCon 2017 Vault Free Tutorial #1: Swift Memory Management

$
0
0

We recently released the RWDevCon 2017 Vault Bundle, a collection of 2 advanced workshops, 24 hours of hands-on tutorials, 1.3GB+ of sample projects, and 600+ pages of conference books.

To celebrate its launch, we’re releasing 3 free sample videos from the 2017 Vault so you can check them out and see if you like them.

Today’s free sample video is Swift Memory Management by Ray Fix. Enjoy!

The post RWDevCon 2017 Vault Free Tutorial #1: Swift Memory Management appeared first on Ray Wenderlich.

Overloading Custom Operators in Swift

$
0
0
Custom Operators

Custom Operators are overloads of fun!

Operators are the core building blocks of any programming language. Can you imagine programming without using + or =?

Operators are so fundamental that most languages bake them in as part of their compiler (or interpreter). The Swift compiler, on the other hand, doesn’t hardcode most operators but instead provides libraries a way to create their own. It leaves the work up to the Swift Standard Library to provide all of the common ones you’d expect. This difference is subtle but opens the door for tremendous customization potential.

Swift operators are particularly powerful because you can alter them to suit your needs in two ways: assigning new functionality to existing operators (known as operator overloading), and creating new custom operators.

A simple example of operator overloading is the addition operator. If you use this operator with two integers, the following happens:

1 + 1 // 2

But if you use the same addition operator with strings, it behaves a little differently:

"1" + "1" // "11"

When + is used with two integers, it adds them arithmetically. But when it’s used with two strings, it concatenates them.

In this tutorial, you’ll explore how you can mold operators to your own needs and build your own 3D vector type in Swift.

Getting Started

Begin by opening Xcode. Create a new playground, name it Operators and select the iOS platform. Delete all the default code so you can start with a blank slate.

Add the following code to your playground:

import UIKit

struct Vector: ExpressibleByArrayLiteral, CustomStringConvertible {
  let x: Int
  let y: Int
  let z: Int

  var description: String {
    return "(\(x), \(y), \(z))"
  }

  init(_ x: Int, _ y: Int, _ z: Int) {
    self.x = x
    self.y = y
    self.z = z
  }

  init(arrayLiteral: Int...) {
    assert(arrayLiteral.count == 3, "Must initialize vector with 3 values.")
    self.x = arrayLiteral[0]
    self.y = arrayLiteral[1]
    self.z = arrayLiteral[2]
  }
}

Here you define a new Vector type with three properties and two initializers. The CustomStringConvertible protocol and the description computed property let you print the vector as a friendly String.

At the bottom of the playground, add the following lines:

let vectorA: Vector = [1, 3, 2]
let vectorB: Vector = [-2, 5, 1]

The ExpressibleByArrayLiteral protocol provides a frictionless interface to initialize a Vector. The protocol requires a non-failable initializer with a variadic parameter: init(arrayLiteral: Int…).

Here’s what that means: The variadic parameter ... lets you pass in an unlimited number of values separated by commas. For example, you can create a Vector like Vector(0) or Vector(5, 4, 3).

The protocol takes convenience a step further and allows you to initialize with an array directly, which is what you’ve done in let vectorA: Vector = [1, 3, 2].

The only caveat to this approach is that you have to accept arrays of any length. If you put this code into an app, keep in mind that it will crash if you pass in an array with a length other than exactly three. The assertion at the top of the initializer will alert you in the console during development and internal testing if you ever try to initialize a Vector with less than or more than three values for the dimensions.

Vectors alone are nice, but it would be even better if you could do things with them. Just as you did in grade school, you’ll start your learning journey with addition.

Overloading the Addition Operator

In order to overload an operator, you have to implement a function whose name is the operator symbol.

Note: You may define the overload function as a member of a type as will be done in this tutorial. When doing so, it must be declared static so it is accessible without an instance of the type it is defined within.

Add the following function at the end of the Vector implementation, just before the closing curly brace:

static func +(left: Vector, right: Vector) -> Vector {
  return [left.x + right.x, left.y + right.y, left.z + right.z]
}

This function will take two vectors in and return the sum vector. To add vectors, you simply need to add each individual component.

Now, to test this function, add the following to the bottom of the playground:

vectorA + vectorB // (-1, 8, 3)

You can see the resultant vector in the right-hand sidebar in the playground.

Other Types of Operators

The addition operator is what is known as an infix operator, meaning that it is used between two different values. There are other types of operators as well:

infix: Used between two values, like the addition operator (e.g. 1 + 1)
prefix: Added before a value, like the negative operator (e.g. -3).
postfix: Added after a value, like the force-unwrap operator (e.g. mayBeNil!)
ternary: Two symbols inserted between three values. In Swift, user defined ternary operators are not supported and there is only one built-in ternary operator which you can read about in Apple’s documentation.

The next operator you’ll want to overload is the negative sign, which will take vectorA, which is (1, 3, 2), and return (-1, -3, -2).

Add this code to the end of the Vector implementation:

static prefix func -(vector: Vector) -> Vector {
  return [-vector.x, -vector.y, -vector.z]
}

Operators are assumed to be infix, so if you want your operator to be a different type, you’ll need to specify the operator type in the function declaration. The negation operator is not infix, so you added the prefix modifier to the function declaration.

At the bottom of the playground, add the line:

-vectorA // (-1, -3, -2)

Check for the correct result in the sidebar.

Next is subtraction, which I will leave to you to implement yourself. When you finish, check to make sure your code is similar to mine. Hint: subtraction is the same thing as adding a negative.

Give it a shot, and if you need hep, check the solution below!

Solution Inside: Solution SelectShow>

Now test the new operator out by adding this code to the bottom of the playground:

vectorA - vectorB // (3, -2, 1)

Mixed Parameters? No Problem!

You can also multiply vectors by a number through scalar multiplication. To multiply a vector by two, you multiply each component by two. You’re going to implement this next.

One thing you need to consider is the order of the arguments. When you implemented addition, order didn’t matter because both parameters were vectors.

For scalar multiplication, you need to account for Int * Vector and Vector * Int. If you only implement one of these cases, the Swift compiler will not automatically know that you want it to work in the other order.

To implement scalar multiplication, add the following two functions to the end of the implementation for Vector:

static func *(left: Int, right: Vector) -> Vector {
  return [right.x * left, right.y * left, right.z * left]
}

static func *(left: Vector, right: Int) -> Vector {
  return right * left
}

To avoid writing the same code multiple times, you simply write the second function using the first.

In mathematics, vectors have another interesting operation known as the cross-product. How cross-products work is beyond the scope of this tutorial, but you can learn more about it on the Cross_product Wikipedia page.

Because using custom symbols is discouraged in most cases (who wants to open the Emoji menu while coding?), it would be very convenient to reuse the asterisk for cross-product.

Cross-products, unlike scalar multiplication, take two vectors as parameters and return a new vector.

Add the following code to add the cross-product implementation at the bottom of the Vector implementation:

static func *(left: Vector, right: Vector) -> Vector {
  return [left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x]
}

Now, add the following calculation to the bottom of the playground:

vectorA * 2 * vectorB // (-14, -10, 22)

This code finds the scalar multiple of vectorA and 2, then finds the cross-product of that vector with vectorB. Note that the asterisk operator always goes from left to right, so the previous code is the same as if you had used parentheses to group the operations, like (vectorA * 2) * vectorB.

Protocol Operators

Some protocols are required members of protocols. For example, a type that conforms to Equatable must implement the == operator. Similarly, a type that conforms to Comparable must implement at least < (and optionally >, >=, and <=)

For Vector, Comparable doesn't really make a lot of sense, but Equatable does, since two vectors are equal if their components are all equal. You’ll implement Equatable next.

To conform to the protocol, add this to the end of the declaration for Vector:

struct Vector: ExpressibleByArrayLiteral, CustomStringConvertible, Equatable {

Xcode will now be yelling at you that Vector does not conform to Equatable. That's because you haven't yet implemented ==. To do that, add the following static function to the bottom of the Vector implementation:

static func ==(left: Vector, right: Vector) -> Bool {
  return left.x == right.x && left.y == right.y && left.z == right.z
}

Add the following line to the bottom of your playground to test this out:

vectorA == vectorB // false

This line returns false as expected because vectorA has different components than vectorB.

Creating Custom Operators

Remember how I said that using custom symbols is usually discouraged? As always, there are exceptions to the rule.

A good way to think about custom symbols is that they should only be used if the following are true:

  • Their meanings are well-known or would make sense to someone reading the code.
  • They are easy to type on the keyboard.

This last operator you will implement matches both of these conditions. The vector dot-product takes two vectors and returns a single scalar number. This is done by multiplying each value in a vector by its counterpart in the other vector, and adding up all these products.

The symbol for dot-product is , which can be easily typed using Option-8 on your keyboard.

You might be thinking, "I can just do the same thing I did with every other operator in this tutorial, right?"

Unfortunately, you can't do that just yet. In the other cases, you are overloading an operator that already exists. For new custom operators, you need to create the operator first.

Directly underneath the Vector implementation, but above the line starting with let vectorA..., add the following declaration:

infix operator •: AdditionPrecedence

This defines as an operator that must be placed between two other values and has the same precedence as the addition + operator. Ignore precedence just for the moment because you will come back to it.

Now that this operator has been registered, add its implementation to the Vector body:

static func •(left: Vector, right: Vector) -> Int {
  return left.x * right.x + left.y * right.y + left.z * right.z
}

Add the following code to the bottom of the playground to test this out:

vectorA • vectorB // 15

Everything looks good so far...or does it? Try the following code at the bottom of the playground:

vectorA • vectorB + vectorA // Error!

Xcode isn't very happy with you. But why?

Right now, and + have the same precedence, so the compiler parses the expression from left to right. Your code is interpreted as:

(vectorA • vectorB) + vectorA

This expression boils down to Int + Vector, which you haven’t implemented, and don't plan to implement. What can you do to fix this?

Precedence Groups

All operators in Swift belong to a precedence group, which describes the order in which operators should be evaluated. Remember learning PEMDAS in elementary school math? That is basically what you are dealing with here.

In the Swift standard library, the order of precedence is as follows:

Swift custom operators precedence and associativity table

Here are a few notes about these operators, since you may not have seen them before:

  1. Bitwise shift operators, << and >>, are used for binary calculations.
  2. You use casting operators, is and as, to determine or change a value's type.
  3. The nil coalescing operator, ??, helps convert optionals into non-optionals.
  4. If your custom operator does not specify a precedence, default precedence is automatically assigned.
  5. The ternary operator, ? :, is analogous to an if-else statement.
  6. AssignmentPrecedence, for the derivatives of =, is evaluated after everything else no matter what.

Types that have a left associativity are parsed so that v1 + v2 + v3 == (v1 + v2) + v3. The opposite is true for right associativity.

Operators are parsed in the order they appear in the table. Try to rewrite the following code using parentheses:

v1 + v2 * v3 / v4 * v5 == v6 - v7 / v8

When you're ready to check your math, look at the solution below.

Solution Inside: Solution SelectShow>

In most cases, you'll want to add parentheses to make your code easier to read. Either way, it's useful to understand the order in which the compiler evaluates operators.

Dot Product Precedence

Your new dot-product doesn’t really fit into any of these categories. It has to be less than addition (as you realized before), but does it really fit into CastingPrecedence or RangeFormationPrecedence?

Instead, you are going to make your own precedence group for your dot-product operator.

Replace your original declaration of the operator with the following:

precedencegroup DotProductPrecedence {
  lowerThan: AdditionPrecedence
  associativity: left
}

infix operator •: DotProductPrecedence

Here, you create a new precedence group named DotProductPrecedence. You place it lower than AdditionPrecedence because you want addition to take precedence. You also make it left-associative because you want it evaluated from left-to-right as you do in addition and multiplication. Then you assign your operator to this new precedence.

Note: In addition to lowerThan, you can also specify higherThan in your DotProductPrecedence. This becomes important if you have multiple custom precedence groups in a single project.

Your old line of code now runs and returns as expected:

vectorA • vectorB + vectorA // 29

Congratulations — you've mastered custom operators!

Where to Go From Here?

Here is the finished playground from this tutorial.

At this point, you know how to bend Swift operators to your needs. In this tutorial, you focused on using operators in a mathematical context. In practice, you’ll find many more ways to use operators.

A great demonstration of custom operator usage can be seen in the ReactiveSwift framework. One example is <~ for binding, an important function in reactive programming. Here is an example of this operator in use:

let (signal, observer) = Signal.pipe()
let property = MutableProperty(0)
property.producer.startWithValues {
  print("Property received \($0)")
}

property <~ signal

Cartography is another framework that heavily uses operator overloading. This AutoLayout tool overloads the equality and comparison operators to make NSLayoutConstraint creation simpler:

constrain(view1, view2) { view1, view2 in
    view1.width   == (view1.superview!.width - 50) * 0.5
    view2.width   == view1.width - 50
    view1.height  == 40
    view2.height  == view1.height
    view1.centerX == view1.superview!.centerX
    view2.centerX == view1.centerX

    view1.top >= view1.superview!.top + 20
    view2.top == view1.bottom + 20
}

Additionally, you can always reference the official custom operator documentation from Apple.

Armed with these new sources of inspiration, you can go out into the world and make your code simpler with operator overloading. Just be careful not to go too crazy with custom operators! :]

If you have any questions or comments on this tutorial, please join the discussion below!

The post Overloading Custom Operators in Swift appeared first on Ray Wenderlich.

Video Tutorial: Practical Instruments Part 3: Time Profiler

Getting Started with fastlane: Creating Provisioning Profiles

RWDevCon 2017 Vault Free Tutorial #2: Swift Playgrounds in Depth

$
0
0

We recently released the RWDevCon 2017 Vault Bundle, a collection of 2 advanced workshops, 24 hours of hands-on tutorials, 1.3GB+ of sample projects, and 600+ pages of conference books.

To celebrate its launch, we’re releasing 3 free sample videos from the vault so you can check them out and see if you like them.

Today’s free sample video is Swift Playgrounds in Depth by Jawwad Ahmad. Enjoy!

The post RWDevCon 2017 Vault Free Tutorial #2: Swift Playgrounds in Depth appeared first on Ray Wenderlich.

Server Side Swift with Perfect: Beautifying Pages with Skeleton


Video Tutorial: Practical Instruments Part 4: Optimizing Launch

RWDevCon 2017 Vault Free Tutorial #3: Server Side Swift with Perfect

$
0
0

We recently released the RWDevCon 2017 Vault Bundle, a collection of 2 advanced workshops, 24 hours of hands-on tutorials, 1.3GB+ of sample projects, and 600+ pages of conference books.

To celebrate its launch, we’re releasing 3 free sample videos from the vault so you can check them out and see if you like them.

Today’s free sample video is Server Side Swift with Perfect by yours truly. Enjoy!

The post RWDevCon 2017 Vault Free Tutorial #3: Server Side Swift with Perfect appeared first on Ray Wenderlich.

Swift Algorithm Club: April 2017 Digest

$
0
0

SwiftAlgClub-Sept-Digest-feature

The Swift Algorithm Club is a popular open source project to implement popular algorithms and data structures in Swift, with over 12,000 stars on GitHub.

We periodically give status updates with how things are going with the project. This month’s update contains 3 big pieces of news:

  • Swift Algorithm Club Workshop at RWDevCon 2017
  • Contributor Note: Github Links Change
  • April Repository Update

Let’s dig in!

Swift Algorithm Club Workshop at RWDevCon 2017

The Swift Algorithm Club ran a worksop at RWDevCon 2017 this year!

The workshop was led by Vincent Ngo and Kelvin Lau, and it followed the following pattern:

  • We gave attendees a Playground with a Swift data structure (such as a linked list), and explained how it worked.
  • Attendees then tried to solve a challenge given the data structure, such as “write a method to find the middle element of the linked list.”
  • Finally, we presented the official solution, with a detailed explanation.

The response to the workshop was phenomenal, with an average 4.95/5 rating for the workshop.

We had a great time learning and speaking, which culminated with some fab loot and some bad dancing:

What in the world is he doing?

Is he having a stroke?

Since this workshop was such as success, we hope to bring these as interactive challenges on raywenderlich.com soon. Stay tuned!

Contributor Note: Github Links Change

A quick note for Swift Algorithm Club contributors.

This month, GitHub changed the way they handled white-spaces for path references:

[Merge Sort](Merge Sort/)

Unfortunately, GitHub no longer do percent encoding for us. This led to countless broken links in our repository. For future reference, you’d want to add the percent encoding yourself:

[Merge Sort](Merge%20Sort/)

April Repository Updates

As always, the repository has seen many updates and polish on existing material. This month, we also gave the repository a new contributions guideline, and added some templates for creating new issues and PRs.

New: Strassen’s Matrix Multiplication Algorithm

Richard Ash has contributed a new algorithm for the repo! This contribution focuses on improving a naive O(n^3) matrix multiplication algorithm. Here’s an excerpt from the repo:

Volker Strassen first published his algorithm in 1969. It was the first algorithm to prove that the basic O(n^3) runtime was not optimal.

The basic idea behind Strassen’s algorithm is to split A & B into 8 submatricies and then recursively compute the submatricies of C. This strategy is called Divide and Conquer.

Where To Go From Here?

The Swift Algorithm Club is always looking for new members. Whether you’re here to learn or here to contribute, we’re happy to have you around.

To learn more about the Swift Algorithm Club, check out our introductory article. We hope to see you at the club! :]

The post Swift Algorithm Club: April 2017 Digest appeared first on Ray Wenderlich.

RWDevCon 2017 Vault Giveaway Winners – And Last Day for Discount!

$
0
0

RWDevCon 2017 Vault Giveaway

Thank you for being a part of the RWDevCon 2017 Vault Week!

During the RWDevCon 2017 Vault week, we released three free video tutorials from RWDevCon 2017:

  1. Swift Memory Management
  2. Swift Playgrounds in Depth
  3. Server Side Swift with Perfect

And of course, we released the RWDevCon 2017 Vault Bundle itself: a collection of 2 advanced workshops, 24 hours of hands-on tutorials, 1.3GB+ of sample projects, and 600+ pages of conference books. But now, it’s time to say goodbye.

But first, there’s two important pieces of news!

RWDevCon 2017 Vault Giveaway Winners

To celebrate the RWDevCon 2017 Vault Week, we had a giveaway for three free copies of the RWDevCon 2017 Vault Bundle. All you had to do to enter was comment on the announcement post.

We had over 100 applicants, and we’ve selected some random winners from among them.

And now it’s time to announce the 3 lucky winners… drum roll please!

The 3 lucky RWDevCon 2017 Vault winners are: kogimobile, zephou, and serdarbuhan. Congratulations! :]

Each winner will receive a free copy of the RWDevCon 2017 Vault Bundle (or a PDF of their choice if they already have a copy). We will be in touch with the winners directly via email.

Last Day for Discount!

Finally I’d like to remind everyone that today is the last day for the current discounted price of the RWDevCon Vault.

Starting tomorrow, each Vault will be raised to its normal price ($100 more). So be sure to grab the 50% off discount while you still can!

Thanks to everyone who entered the RWDevCon 2017 Vault giveaway, bought the vault, or simply read these posts. We really appreciate each and every one of you, and thank you for your support and encouragement – it is so amazing being a part of this community.

We hope you enjoy your virtual trip to RWDevCon 2017, and we hope to see you at the actual conference next year! :]

The post RWDevCon 2017 Vault Giveaway Winners – And Last Day for Discount! appeared first on Ray Wenderlich.

Readers’ App Reviews – April 2017

$
0
0

A new Mac Pro is on the way! I was as surprised as you to hear the news.

I’m very excited to see what Apple has in store for a modern pro device. But sadly, we’ll have to wait a little while longer.

While we’re waiting, I’d like to share the latest apps released by readers like you. These are apps built with the help of our books, videos, and free tutorials.

This month I’m sharing:

  • An app to help you count calories
  • A game for the math wiz in all of us
  • An app to keep our hard drives tidy
  • And of course, much more!

Keep reading to see the latest apps released by raywenderlich.com readers like you.

FoodMood


Losing or gaining weight can be a hard task. Often times its not just about exercise but dietary changes. But keeping track of those dietary changes can be the hardest part.

FoodMood is a food diary that will motivate you to eat better and help you keep track or what you eat for each meal. You’ll be able to track what you ate for each meal or snack every day. FoodMood will tally your calories and keep an eye on your daily budget.

It also tracks a few extra things that can help you. Each time you eat it asks if you ate because you were hungry, craving, or sad. Sometimes its not just hunger that drives us!

It also allows you to see analysis of your hungriest times of the day be that Breakfast, Lunch, or Dinner. Getting an idea of where your largest intakes are might help you figure out areas to cut or when you should consider exercise.

If you’re tracking your diet, you should give FoodMood a change to help you track it better.

Divi.


If you’ve been hoping to practice your division and prime factor skills while having some fun at the same time, look no further!

Divi is a game entirely focused on quick identification of multiples and prime factors. You’ll see a number and be asked if it is divisible by one of two numbers, both, or neither. The game play is that simple. Once your mind warms up it can be quite addicting to see how far you can get.

Divi has 3 game modes, Classic, Rush, and Endless. Endless is just a stream where you last as long as you can without getting an answer wrong. Rush gives you 60 seconds to get as many as you can correct. Classic gives you 10 seconds per number but if you get one wrong its over.

Give Divi a try, you might be surprised how hard it is to quickly calculate prime factors.

Things Speak


ThingSpeak is an open source Internet of Things data monitoring protocol used for all sorts of things from weather polling, to energy consumption tracking, to solar installation management. There are tons of public channels with lots of information available. Things Speak will unlock all that right on your iPhone or iPad.

Just enter a channel number and Things Speak will pull down the latest data available. You can adjust tons of settings starting with how many of the latest values you’d like to see. Adjust visualization settings for the graph and how the data is presented be that normal, averaged, or summed up. Things Speak supports up to 8 fields of data from each channel.

Things Speak also makes it easy to favorite channels for ones you frequently check on. And if you’re checking a channel’s data really frequently you can even set up a widget that will show you the latest data at all times. Perfect for your personal weather polling station perhaps.

Colourinz


Colourinz is a an adult coloring book right on your iPhone or iPad.

Coloring for adults has had an uptick in recent years. Color can be very relaxing while helping you flex your creative side. This app gives you beautiful and detailed works of art to fill in with colors of your choice.

The color palettes are organized and easy to use. The drawing is responsive. Even on your small iPhone using your finger, its easy to pinch to zoom and color just the section you’re aiming for.

Download Colourinz today and color to your hearts content anywhere you are.

Tank Tank One – World War 2 Hero


Tank Tank One is a real time artillery battle in your pocket!

Take control of a tank on the field in a battle for its life. Large battlefields before you to be conquered. You can drive your tank left or right on command and fire at will. Try to destroy the other tanks before they destroy you. Each shell you fire can leave a crater in a ground. Be careful of your reckless fire to avoid destroying your road to victory. Realistic physics break away the ground with each explosion.

It will take strategy and reflexes to conquer these enemies. But for each victory you are handsomely rewarded. Unlock bonuses and new units. Tank Tank One is easy to pick up and learn but you’ll have to practice to become the best.

Tap! Tap! Tap!


Tap! Tap! Tap! is a unique and addictive block breaking game. These Vikings need your help holding off a wave of mindless blocks!

Unlike most block breaking games, this one expands to the right instead of up. A column on the left is dropped into place pushing everything down every few seconds. You’re looking for matching blocks to tap and eliminate in pairs or more.

The longer you can last breaking enough blocks to prevent the columns from reaching the right side, the better. Try to beat your own highscores or challenge yourself and take on the world!

  • Author: Karol Kędziora
  • Most useful tutorial: 2D Apple Games by Tutorials
  • App Store Link: Check it out!
  • App Cleaner & Uninstaller


    We all need to clear out some space on our hard drives from time to time. Old applications, leftover app files, caches, logs, system extensions, and more all begin to clog up our system over time.

    App Cleaner & Uninstaller is here to help! It will scan your system for everything you might want to get rid of and estimate how much space you’d save if each item were deleted. Not only can it find old apps and their leftovers, it can also help in other ways. It can reset applications to their first launch state. It can help you find launch agents and system daemons. It can show you login items so you can pick the ones you want to keep. It can find all system extensions and let you remove them.

    App Cleaner & Uninstaller will scan your hard drive for free and highlight what should be removed. It can even remove leftovers and service files for free. After that if you really want to be squeaky clean, grab the pro in app purchase to unlock full executable removal and more.

    Where To Go From Here?

    Each month, I really enjoy seeing what our community of readers comes up with. The apps you build are the reason we keep writing tutorials. Make sure you tell me about your next one, submit here.

    If you saw an app your liked, hop to the App Store and leave a review! A good review always makes a dev’s day. And make sure you tell them you’re from raywenderlich.com; this is a community of makers.

    If you’ve never made an app, this is the month! Check out our free tutorials to become an iOS star. What are you waiting for – I want to see your app next month.

    The post Readers’ App Reviews – April 2017 appeared first on Ray Wenderlich.

    Viewing all 4373 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>