Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

Wednesday, November 23, 2016

How to Isolate Client-Server Interaction Logic in iOS Applications

Nowadays most mobile applications rely heavily on client-server interactions. Not only does this mean that can they offload most of their heavy tasks to backend servers, but it also allows these mobile applications to offer all sorts of features and functionality that can only be made available through the Internet.
Backend servers are usually designed to offer their services through RESTful APIs. For simpler applications, we often feel tempted to get by creating spaghetti code; mixing code that invokes the API with rest of the application logic. However as applications grow complex and deal with more and more APIs, it can become a nuisance to interact with these APIs in an unstructured, unplanned manner.
Keep your iOS application code clutter-free with a well-designed REST client networking module.Keep your iOS application code clutter-free with a well-designed REST client networking module.
This article discusses an architectural approach for building a clean REST client networking module for iOS applications that allows you to keep all of your client-server interaction logic isolated from rest of your application code.

Client-Server Applications

A typical client-server interaction looks something like this:
  1. A user performs some action (e.g., tapping on some button or performing some other gesture on the screen).
  2. The application prepares and sends an HTTP/REST request in response to the user action.
  3. The server processes the request and responds accordingly to the application.
  4. The application receives the response and updates the user interface based on it.
At quick glance, the overall process may look simple, but we do have to think about the details.
Even assuming that a backend server API works as advertised (which is not always the case!), it can often be poorly designed making it inefficient, or even difficult, to use. One common annoyance is that all calls to the API require the caller to redundantly provide the same information (e.g., how request data is formatted, an access token that the server can use to identify the currently signed in user, and so on).
Mobile applications may also need to utilize multiple back-end servers concurrently for different purposes. One server may, for example, be dedicated to user authentication while another deals with collecting analytics only.
Furthermore, a typical REST client will need to do way more than just invoke remote APIs. The ability to cancel pending requests, or a clean and manageable approach to handling errors, are examples of functionality that needs to be built into any robust mobile application.

An Overview of the Architecture

The core of our REST client will be built on these following components:
  • Models: Classes that describe the data models of our application, reflecting the structure of data received from, or sent to, the backend servers.
  • Parsers: Responsible for decoding server responses and producing model objects.
  • Errors: Objects to represent erroneous server responses.
  • Client: Sends requests to backend servers and receives responses.
  • Services: Manage logically linked operations (e.g. authentication, managing user related data, analytics, etc).
This is how each of these components will interact with each other:
The arrows 1 through 10 in the image above show an ideal sequence of operations between the application invoking a service and the service eventually returning the requested data as a model object. Each component in that flow has a specific role ensuring separation of concerns within the module.

Implementation

We will implement our REST client as part of our imaginary social network application into which we will load a list of the currently logged in user’s friends. We will assume our remote server uses JSON for responses.
Let us begin by implementing our models and parsers.

From Raw JSON to Model Objects

Our first model, User, defines the structure of information for any user of the social network. To keep things simple, we will only include fields that are absolutely necessary for this tutorial (in a real application, the structure would typically have a lot more properties).
struct User {
    var id: String
    var email: String?
    var name: String?
}
Since we will receive all user data from the backend server via its API, we need a way to parse the API response into a valid User object. To do this, we will add a constructor to User that accepts a parsed JSON object (Dictionary) as a parameter. We will define our JSON object as an aliased type:
typealias JSON = [String: Any]
We will then add the constructor function to our User struct as follows:
extension User {
    init?(json: JSON) {
        guard let id = json["id"] as? String else {
            return nil
        }
        
        self.id = id
        self.email = json["email"] as? String
        self.name = json["name"] as? String
    }
}
To preserve the original default constructor of User, we add the constructor through an extension on the User type.
Next, to create a User object from a raw API response, we need to perform the following two steps:
// Transform raw JSON data to parsed JSON object using JSONSerializer (part of standard library)
let userObject = (try? JSONSerialization.jsonObject(with: data, options: [])) as? JSON
// Create an instance of `User` structure from parsed JSON object
let user = userObject.flatMap(User.init)

Streamlined Error Handling

We will define a type to represent different errors that may occur when attempting to interact with the backend servers. We can divide all such errors into three basic categories:
  • No Internet connectivity
  • Errors that reported as a part of the response (e.g. validation errors, insufficient access rights, etc.)
  • Errors that the server fails to report as a part of the response (e.g. server crash, responses timing out, etc.)
We can define our error objects as an enumeration type. And while we are at it, it is a good idea to make our ServiceError type conform to the Error protocol. This will allow us to use and handle these error values using standard mechanisms provided by Swift (such as using throw to throw an error).
enum ServiceError: Error {
    case noInternetConnection
    case custom(String)
    case other
}
Unlike noInternetConnection and other errors, the custom error has a value associated with it. This will allow us to use the error response from the server as an associated value for the error itself, thereby giving the error more context.
Now, let’s add a errorDescription property to the ServiceError enumartion to make the errors more descriptive. We will add hardcoded messages for the noInternetConnection and other errors and use the associated value as the message for custom errors.
extension ServiceError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .noInternetConnection:
            return "No Internet connection"
        case .other:
            return "Something went wrong"
        case .custom(let message):
            return message
        }
    }
}
There is just one more thing we need to implement in our ServiceError enumeration. In the case of a customerror, we need to transform the server JSON data into an error object. To do this, we use the same approach we used in the case of models:
extension ServiceError {
    init(json: JSON) {
        if let message =  json["message"] as? String {
            self = .custom(message)
        } else {
            self = .other
        }
    }
}

Bridging the Gap Between the Application and Backend Server

The client component will be an intermediary between the application and the backend server. It’s a critical component that will define how the application and the server will communicate, yet it will know nothing about the data models and their structures. The client will be responsible for invoking specific URLs with provided parameters and returning incoming JSON data parsed as JSON objects.
enum RequestMethod: String {
    case get = "GET"
    case post = "POST"
    case put = "PUT"
    case delete = "DELETE"
}


final class WebClient {
    private var baseUrl: String
    
    init(baseUrl: String) {
        self.baseUrl = baseUrl
    }
    
    func load(path: String, method: RequestMethod, params: JSON, completion: @escaping (Any?, ServiceError?) -> ()) -> URLSessionDataTask? {
        // TODO: Add implementation 
    }
}
Let’s examine what’s happening in the above code…
First, we declared an enumeration type, RequestMethod, that describes four common HTTP methods. These are among the methods used in REST APIs.
The WebClient class contains the baseURL property which will be used to resolve all relative URLs that it receives. In case our application needs to interact with multiple servers, we can create multiple instances of WebClient each with a different value for baseURL.
The Client has a single method load, which takes a path relative to baseURL as a parameter, request method, request parameters, and completion closure. The completion closure is invoked with the parsed JSON and ServiceError as parameters. For now, the method above lacks an implementation, which we will get to shortly.
Before implementing the load method, we need a way to create a URL from all the information available to the method. We will extend the URL class for this purpose:
extension URL {
    init(baseUrl: String, path: String, params: JSON, method: RequestMethod) {
        var components = URLComponents(string: baseUrl)!
        components.path += path
        
        switch method {
        case .get, .delete:
            components.queryItems = params.map {
                URLQueryItem(name: $0.key, value: String(describing: $0.value))
            }
        default:
            break
        }
        
        self = components.url!
    }
}
Here we simply add the path to the base URL. For GET and DELETE HTTP methods, we also add the query parameters to the URL string.
Next, we need to be able to create instances of URLRequest from given parameters. To do this we will do something similar to what we did for URL:
extension URLRequest {
    init(baseUrl: String, path: String, method: RequestMethod, params: JSON) {
        let url = URL(baseUrl: baseUrl, path: path, params: params, method: method)
        self.init(url: url)
        httpMethod = method.rawValue
        setValue("application/json", forHTTPHeaderField: "Accept")
        setValue("application/json", forHTTPHeaderField: "Content-Type")
        switch method {
        case .post, .put:
            httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
        default:
            break
        }
    }
}
Here, we first create a URL using the constructor from the extension. Then we initialize an instance of URLRequest with this URL, set a few HTTP headers as necessary, and then in case of POST or PUT HTTP methods, add parameters to the request body.
Now that we have covered all the prerequisites, we can implement the load method:
final class WebClient {
    private var baseUrl: String
    
    init(baseUrl: String) {
        self.baseUrl = baseUrl
    }
    
    func load(path: String, method: RequestMethod, params: JSON, completion: @escaping (Any?, ServiceError?) -> ()) -> URLSessionDataTask? {
        // Checking internet connection availability
        if !Reachability.isConnectedToNetwork() {
            completion(nil, ServiceError.noInternetConnection)
            return nil
        }




        // Adding common parameters
        var parameters = params
        
        if let token = KeychainWrapper.itemForKey("application_token") {
            parameters["token"] = token
        }




        // Creating the URLRequest object
        let request = URLRequest(baseUrl: baseUrl, path: path, method: method, params: params)




        // Sending request to the server.
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            // Parsing incoming data
            var object: Any? = nil
            if let data = data {
                object = try? JSONSerialization.jsonObject(with: data, options: [])
            }
            
            if let httpResponse = response as? HTTPURLResponse, (200..<300) ~= httpResponse.statusCode {
                completion(object, nil)
            } else {
                let error = (object as? JSON).flatMap(ServiceError.init) ?? ServiceError.other
                completion(nil, error)
            }
        }
        
        task.resume()
        
        return task
    }
}
The load method above performs the following steps:
  1. Check availability of the Internet connection. If Internet connectivity is not available, we call the completion closure immediately with noInternetConnection error as a parameter. (Note: Reachability in the code is a custom class, which uses one of the common approaches to check the Internet connection.)
  2. Add common parameters.. This can include common parameters such as an application token or user id.
  3. Create the URLRequest object, using the constructor from the extension.
  4. Send the request to the server. We use the URLSession object to send data to the server.
  5. Parse incoming data. When the server responds, we first parse the response payload into a JSON object using JSONSerialization. Then we check the status code of the response. If it is a success code (i.e., in the range between 200 and 299), we call the completion closure with the JSON object. Otherwise, we transform the JSON object into a ServiceError object and call the completion closure with that error object.

Defining Services for Logically Linked Operations

In the case of our application, we need a service that will deal with tasks related to friends of a user. For this, we create a FriendsService class. Ideally, a class like this will be in charge of operations such as getting a list of friends, adding a new friend, removing a friend, grouping some friends into a category, etc. For simplicity in this tutorial, we will implement just one method:
final class FriendsService {
    private let client = WebClient(baseUrl: "https://your_server_host/api/v1")
    
    @discardableResult
    func loadFirends(forUser user: User, completion: @escaping ([User]?, ServiceError?) -> ()) -> URLSessionDataTask? {


        let params: JSON = ["user_id": user.id]
        
        return client.load(path: "/friends", method: .get, params: params) { result, error in
            let dictionaries = result as? [JSON]
            completion(dictionaries?.flatMap(User.init), error)
        }
    }
}
The FriendsService class contains a client property of type WebClient. It is initialized with the base URL of the remote server which is in charge of managing friends. As previously mentioned, in other service classes, we can have a different instance of WebClient initialized with a different URL if necessary.
In the case of an application that works with only one server, the WebClient class can be given a constructor that initializes with that server’s URL:
final class WebClient {
    // ...
    init() {
        self.baseUrl = "https://your_server_base_url"
    }
    // ...
}
The loadFriends method, when invoked, prepares all the necessary parameters and uses FriendService’s instance of WebClient to make an API request. After it receives the response from the server through the WebClient, it transforms the JSON object into User models and calls the completion closure with them as a parameter.
A typical usage of the FriendService may look something like the following:
let friendsTask: URLSessionDataTask!
let activityIndicator: UIActivityIndicatorView!
var friends: [User] = []


func friendsButtonTapped() {
 
       friendsTask?.cancel() //Cancel previous loading task.




       activityIndicator.startAnimating() //Show loading indicator


 friendsTask = FriendsService().loadFriends(forUser: currentUser) {[weak self] friends, error in
DispatchQueue.main.async {
      self?.activityIndicator.stopAnimating() //Stop loading indicators 
            if let error = error {
                print(error.localizedDescription) //Handle service error
            } else if let friends = friends {
                 self?.friends = friends //Update friends property
                 self?.updateUI() //Update user interface
            }
}
      }
}
In the above example, we are assuming that the function friendsButtonTapped is invoked whenever the user taps on a button intended to show them a list of their friends in the network. We also keep a reference to the task in the friendsTask property so that we can cancel the request at any time by calling friendsTask?.cancel().
This allows us to have a greater control of the lifecycle of pending requests, enabling us to terminate them when we determine that they have become irrelevant.

Conclusion

In this article, I have shared a simple architecture of a networking module for your iOS application that is both trivial to implement and can be adapted to the intricate networking needs of most iOS applications. However, the key takeaway from this is that a properly designed REST client and components accompanying it – that are isolated from the rest of your application logic – can help keep your application’s client-server interaction code simple, even as the application itself becomes increasingly complex.
I hope you find this article helpful in building your next iOS application. You can find the source code of this networking module on GitHub. Check out the code, fork it, change it, play with it.
If you find some other architecture more preferable for you and your project, please do share the details in the comments section below.
This article was originally posted on Toptal

Monday, March 28, 2016

The Vital Guide to Interviewing Mobile Application Designers - Kapil Sharma

This guide deals with mobile application design and its goal is to provide clients with information on mobile design, and help them recognize a top notch mobile designer. It touches on multiple aspects of mobile application development, some or all of which will be relevant to the specific context in which you are looking to hire.
Before we proceed to define what makes a top-notch designer, we need to be aware of the definition.
Mobile application designers focus on native mobile apps and work closely with UX and UI designers to apply their design to mobile interfaces.
Mobile application designers focus on native mobile apps and work closely with UX and UI designers to apply their design to mobile interfaces.
Mobile designers have many names and some of them are app designers, iOS designers, Android designers, and so on. They usually work closely with user-experience (UX) designers and user-interface (UI) designers to apply their design to mobile interfaces. Their main focus is on native mobile applications, but they should also be able to create designs for mobile and hybrid apps.
Every mobile application designer should be aware of the difference between these three platforms.

The Challenge

Native apps live on the device and they are accessed through icons on the device home screen. Native apps are usually installed through an application store (such as Google Play or Apple’s App Store). They are specifically developed for one platform, and can take full advantage of all the device features; they can use the camera, the GPS, various sensors like the accelerometer, compass, and so on. They can also incorporate gestures (either standard operating system gestures or new, app-defined gestures). Also, it’s worth noting that native apps can use the device’s notification system, access local information like the contacts list, and they can work offline.
Responsive web applications are not real applications; they are really websites that, in many ways, look and feel like native applications, but are not implemented as such. They are run by a browser and typically written in HTML5. Users first access them as they would access any web page: They navigate to a special URL and then have the option of “installing” them on their home screen by creating a bookmark to that page. Web apps became popular when HTML5 went mainstream and people realized that they could obtain native-like functionality in the browser.
Today, as more and more sites use HTML5, the distinction between web apps and regular web pages is blurring. For instance, there are no visible browser buttons or bars, although the site runs in Safari (when accessed from an iPhone). Users swipe horizontally to move on to new sections of the app. And, thanks to browser caching, it’s even possible to read the newspaper offline.

HTML5 vs. Native Apps vs. Hybrid Apps

A lot of features are available in HTML5. It possible to access some sensors, implement the tap-to-call feature, and even other functions, such as the device’s camera API. However, few web apps and websites take advantage of these possibilities.
Mobile app developers must be aware of the difference between these native and hybrid apps, as well as HTML5 apps.
Mobile app developers must be aware of the difference between these native and hybrid apps, as well as HTML5 apps.
There are, however, native features that remain inaccessible (at least for now) in the browser:
  • The notification system, running in the background
  • Sensor input such as accelerometer information (other than detecting landscape or portrait orientations)
  • Complex gestures
Of course, one can argue that many apps (native or otherwise) do not take advantage of those extra features, anyhow. But if you really need those native features, you’ll have to create a native app, or at least a hybrid app.
Native mobile apps provide fast performance and a high degree of reliability. It’s important to note that most mobile video games are native applications. We all know that video games are among the most popular mobile applications, and many of them need to utilise the hardware in the most efficient way in order to ensure smooth gameplay and a good user experience.
Hybrid apps are part native apps, part web apps. Because of that, many people incorrectly call them “web apps.” Like native apps, they live in an app store and can take advantage of the many device features available. Like web apps, they rely on HTML being rendered in a browser, with the understanding that the browser is embedded within the app. Often, companies build hybrid apps as wrappers for an existing web page; in that way, they hope to get a presence in the app store without spending resources on app development. Hybrid apps are also popular because they allow cross-platform development and thus significantly reduce development costs: The same HTML code components can be reused on different mobile operating systems.
Tools such as PhoneGap and Sencha Touch allow people to design and code across platforms, using the power of HTML. Doing justice to many of these topics would warrant posts of their own. Nonetheless, this guide is intended to provide, at least, a meaningful overview of key issues and topics relating to mobile application design. Furthermore, every good mobile application designer should be aware of all the terms used in this article.
It’s not unusual for a client to demand native apps rather than responsive web applications. In order to provide a different and unique user-experience on each device, many clients will require a native application.
Q: Native, Web App, or Hybrid: Which Should You Choose?
To summarize, native apps, hybrid apps, or web apps cater to the needs of the mobile user. There is no best solution; each has its strengths and weaknesses. The choice depends on each client’s unique needs.
Q: When designing a new application, what are the most important questions you need to know?
  • What is your app’s main goal?
  • What are the most important sections in your app? How many are there?
  • What kind of actions should be available to the user throughout the app?
  • Who is your direct and indirect competition, if it exists?
  • Which features and functions do you want to include in your app?
With the answers, the designer should be able to start searching for the best design pattern for the new application. Maybe the best question to ask when starting a new design would be: “If you came home angry and stressed out, looking to buy a cinema ticket, how you would like to application to work?”
The same question can be adjusted to any real-life situation and mobile app. If the application design works when the user is frustrated, then the application is probably well designed.
Q: What do you need to consider when designing for iOS, Android or any mobile platform?
When people are about to use something, they have already expectations (we call them mental models). For example, most users will buy a certain smartphone because they like the design principles behind its operating system, the appearance, or how the device works. So, the most important thing to consider when designing for iOS, or other mobile platform, is to consider vendor guidelines. While developers need to stick to vendor guidelines, the basic logic behind each application should be identical, regardless of vendor.
Designers should not try to reinvent the wheel by implementing some unexpected elements within the application. In order to provide an extraordinary experience, designers should experiment with improved user flow and interaction design. In the application industry, this is a standard; Apple does it, Google does it, and Microsoft is no exception.
Q: When designing for a diverse set of users who will engage with your products, what do you need to consider?
Along with device platform guidelines, the designer should consider accessibility guidelines for a range of users. Design for people who are young, old, power users, casual users, and those who just enjoy a quality experience. Embrace these accessibility guidelines as you would any set of design constraints. They are part of the challenge of creating amazing products.
Q: Why are application icons so important for an application and what should be considered when designing the icon?
Beautiful, compelling icons are a fundamental part of a good user experience. Far from being merely decorative, icons play an essential role in communicating with users. Focus on a unique shape; some icons have many colors or they feature gradients, but they all start with a simple shape. That allows them to be recognizable at a distance and at a glance. Icons are seen in a range of different sizes. They are large in the App store, get small on the home screen and even smaller in the notification centre and in groups. Make sure your design scales well and is clear at any size.
The designer should also test the icon on different wallpapers; while it might look great against a traditional backdrop, iOS raindrops for example, there’s no guarantee it looks great on all wallpapers. And try grouping your designs into folders to evaluate how they look.
Q: How to design an intuitive user-interface and still achieve the “Wow!” effect.
Intuitive means easy to understand or operate without explicit instruction. The designer should always use different visual treatment for icons that are “tappable” and icons that are used as indicators and are “non-tappable.” Once a coherent system for distinguishing tappable from non-tappable icons is in place, the designer needs to follow it throughout the mobile app. In order to achieve the “WOW effect,” the designer should play around with unique shapes (for example custom made icons), animations, and then present them in a whole new way.
For example, the paper plane is now widely recognized as the “Send” icon. When it was first introduced, it was probably a little bit confusing for a user. “What is this paper plane? What does it have to do with email?” In many applications, the “Save” icon is an image of the extinct floppy disk. A life buoy icon could be used, instead. Once users understand or discover the meaning of a new UI element, it becomes “intuitive” the next time.

Three Components of the “Wow!” Factor

If the designer is limited by brand guidelines, the “Wow!” effect can be achieved in other areas.
Let’s imagine that we have a beautiful and expensive pen. But if it doesn’t write well, we will probably abandon it and go for an ordinary pen that suits our purpose. Fancy, eye-catching design cannot always help an ineffective product, so we must always think about designing an experience that pleasantly surprises the user by helping him to achieve the intended task faster and efficiently.
It is important to note that “Wow!” factors depend on the concept from the UX/visual designer being well executed by the programmer.
Q: Should we use gestures in our mobile application and how will they affect User Experience?
With the integration of gyroscopes and motion sensors, smart devices are able to detect movement. With this, the interaction between the user and the device extends beyond the click and tap, bringing real-life gestures to the screen.
Users are intuitive about gestures. When asked how to delete an item, users tried to move the item out of the screen regardless of age, sex and gender. Enhancing the user experience with fewer taps or scrolling allows applications to become more interactive.
Q: How will 3D Touch technology from Apple change the interface?
Force Touch technology does not enable truly new gestures, it is simply an extension of gestures we are already familiar with. It will help designers and developers to add a Z-axis in order to provide more depth of information on a top layer without touching or overcomplicating the Information Architecture underneath.
Q: How many fonts are recommended and what is the best practice with typography while designing mobile applications?
Reducing the number of fonts on a screen can reveal the power of typography. Instead of using different typefaces and leveraging different characteristics (e.g. italics, bold, semi-bold), different font sizes can better differentiate discrete areas of content. Embracing a singular typeface across an entire app drives consistency not only for branding but also across channels — e.g. app, mobile site, website — thus optimizing the mobile elements across the omnichannel experience. Also, users prefer the simplicity of having one typeface while scrolling for relevant content.
Q: What are micro-interactions and why should we use them?
Micro-interactions are small, visual enhancements (for example, an animation or a sound) occurring around a use case. These scenarios may include completing a transaction, flagging an item, or prompting a pop-up message. Such interactions are subtle, but they differentiate the product by pointing the user’s attention to the right element.
Micro-interactions may be leveraged as a signal to prompt the user while accomplishing a task (adjusting a setting, for instance), thus creating a small piece of content such as a pop-up message. Apps with well designed micro-interactions are considered easier to use, more fun, and more engaging by their users.

Final words

Before designers choose to create something, they must conduct market research in order to learn what’s out there and what they have to do to create a unique and successful design.
The biggest difference between developing a mobile application and a desktop application, or even a website, is context. This is what makes mobile apps so powerful. Each app is used for its own purpose, at a specific time and place. There are several ways to accomplish the same action for mobile, and it’s up to you, the designer, to design and choose the most effective way.

This hiring guide originally appeared in Toptal Engineering blog

Navigating Portfolio Management Services (PMS): Evaluation, Strategy, and Return Dynamics.

  What is Portfolio Management Services (PMS)? Portfolio Management Services (PMS) are customized, professional investment solutions designe...