{"id":96,"date":"2020-12-06T18:30:08","date_gmt":"2020-12-06T18:30:08","guid":{"rendered":"http:\/\/mohammadreza.me\/blog\/?p=96"},"modified":"2020-12-06T18:30:08","modified_gmt":"2020-12-06T18:30:08","slug":"urlrequestconvertible","status":"publish","type":"post","link":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/","title":{"rendered":"Router pattern with Alamofire\u2019s URLRequestConvertible protocol"},"content":{"rendered":"\n<p>If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network and retrieves data from a server. In this tutorial, we learn about Alamofire router pattern which helps us to have a clean network layer and avoid duplication code.<\/p>\n\n\n\n<div style=\"height:24px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Alamofire<\/h2>\n\n\n\n<p>Alamofire is an HTTP networking library written in Swift for iOS, iPadOS, and macOS. It provides an elegant interface on top of Apple\u2019s Foundation networking stack that simplifies several common networking tasks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Alamofire Good For?<\/h2>\n\n\n\n<p>Why do you need Alamofire at all? Apple already provides URLSession and other classes for downloading content via HTTP, so why complicate things with another third party library?<br>The short answer is Alamofire is based on URLSession, but it frees you from writing boilerplate code which makes writing networking code much easier. You can access data on the Internet with very little effort, and your code will be much cleaner and easier to read.<\/p>\n\n\n\n<div style=\"height:24px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p>Here\u2019s an example of the same networking operation with Alamofire\u2019s <strong>request<\/strong> function:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">AF.request(url!, method : .get, encoding : JSONEncoding.default).responseJSON { (response) in\n    switch response.result {\n        case .failure(let error):\n        \/\/ show failure errors\n        case .success(let result):\n        \/\/ do whatever you want after getting success response.\n    }\n}<\/pre>\n\n\n\n<p>If you used Alamofire before, you probably created API manager or some sort of network model in your apps which cause code duplication, because we used to write the URL path, HTTP method and query parameters for each requests.<br>As the app size grows, it\u2019s essential to use some common patterns for building the network stack. But how we can do that? The answer is using <em>URLRequestConvertible<\/em> protocol and <em>Router<\/em> design pattern.<\/p>\n\n\n\n<p>The router is responsible for creating the URL requests so that our API manager (or whatever makes the API calls) doesn\u2019t need to do that.<\/p>\n\n\n\n<div style=\"height:24px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">URLRequestConvertible<\/h2>\n\n\n\n<p>URLRequestConvertible is protocol and it has a single requirement, asURLRequest(), which helps construct a URLRequest.<\/p>\n\n\n\n<div style=\"height:24px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p>Ok lets start.<\/p>\n\n\n\n<p>To start we will declare a router. It will be an enum with case for each type of call we want to make.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import Alamofire\n\nenum UserRouter: URLRequestConvertible {\n    \n    \/\/ 1.\n    case login(user: User)\n    case getUserInfo\n    \n    \/\/ 2.\n    var path: String {\n        switch self {\n        case .login:\n            return \"login\"\n        case .getUserInfo :\n            return \"userInfo\"\n        }\n    }\n    \n    \/\/ 3.\n    var method: HTTPMethod {\n        switch self {\n        case .login:\n            return .post\n        case .getUserInfo:\n            return .get\n        }\n    }\n    \n    \/\/ 4.\n    var parameters: Parameters? {\n        switch self {\n        case .login(let user):\n            return [\n                \"username\" : user.username,\n                \"password\" : user.password\n            ]\n        default:\n            nil\n        }\n    }\n    \n    \/\/ 5.\n    func asURLRequest() throws -> URLRequest {\n       \/\/ 6.\n        let url = try URL(string: Constant.BaseURL.asURL()\n                                                  .appendingPathComponent(path)\n                                                  .absoluteString.removingPercentEncoding!)\n        \/\/ 7.\n        var request = URLRequest.init(url: url!)\n        \/\/ 8.\n        request.httpMethod = method.rawValue\n        \/\/ 9.\n        request.timeoutInterval = TimeInterval(10*1000)\n        \/\/ 10.\n        return try URLEncoding.default.encode(request,with: parameters)\n    }\n\n}<\/pre>\n\n\n\n<ol class=\"wp-block-list\"><li>First, add case for each URLRequest endpoints. Swift enums can have arguments, so we can pass our datas to router.<\/li><li>define the endpoint for each URLRequest.<\/li><li>Add http method like .get, .post, .delete, .put\u2026 for each case.<\/li><li>You can add parameters property to set API parameters.<\/li><li>To conform URLRequestConvertible protocol we must add asURLRequest() function to the router.<\/li><li>In asURLRequest function define url as BaseURL and append path as request endpoint.<\/li><li>Define request as URLRequest.<\/li><li>Add http method to the request.<\/li><li>Optionally, we can add timeout to the request.<\/li><li>Finally, return URLEncoding with request I define earlier.<\/li><\/ol>\n\n\n\n<div style=\"height:24px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p>Done, the login router was created, and now time to use it.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">let configuration = URLSessionConfiguration.af.default\nlet session = Session(configuration: configuration)\nsession.request(UserRouter.login(user: user))\n\t.validate()\n\t.responseData { response in\n             \/\/ Do whatever you wnat with response\n        }<\/pre>\n\n\n\n<div style=\"height:24px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p>That\u2019s all. As you can see we no longer have to declare URL, query parameters, and headers locally for each API call.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network and retrieves data from a server. In this tutorial, we learn about Alamofire router pattern which helps us to have a clean network layer and avoid duplication code. Alamofire Alamofire is &hellip; <a href=\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Router pattern with Alamofire\u2019s URLRequestConvertible protocol<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":122,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[21,23],"class_list":["post-96","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift","tag-alamofire","tag-urlrequestconvertible"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Alamofire URLRequestConvertible - Swift with Reza<\/title>\n<meta name=\"description\" content=\"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network...\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Alamofire URLRequestConvertible - Swift with Reza\" \/>\n<meta property=\"og:description\" content=\"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/\" \/>\n<meta property=\"og:site_name\" content=\"Swift with Reza\" \/>\n<meta property=\"article:published_time\" content=\"2020-12-06T18:30:08+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1621\" \/>\n\t<meta property=\"og:image:height\" content=\"800\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Reza\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Reza\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/\",\"url\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/\",\"name\":\"Alamofire URLRequestConvertible - Swift with Reza\",\"isPartOf\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png\",\"datePublished\":\"2020-12-06T18:30:08+00:00\",\"author\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c\"},\"description\":\"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network...\",\"breadcrumb\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#primaryimage\",\"url\":\"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png\",\"contentUrl\":\"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png\",\"width\":1621,\"height\":800,\"caption\":\"URLRequestConvertible\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/mohammadreza.me\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Router pattern with Alamofire\u2019s URLRequestConvertible protocol\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/#website\",\"url\":\"https:\/\/mohammadreza.me\/blog\/\",\"name\":\"Swift with Reza\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/mohammadreza.me\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c\",\"name\":\"Reza\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g\",\"caption\":\"Reza\"},\"sameAs\":[\"http:\/\/mohammadreza.me\/blog\"],\"url\":\"https:\/\/mohammadreza.me\/blog\/author\/mohammadreza\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Alamofire URLRequestConvertible - Swift with Reza","description":"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network...","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/","og_locale":"en_US","og_type":"article","og_title":"Alamofire URLRequestConvertible - Swift with Reza","og_description":"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network...","og_url":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/","og_site_name":"Swift with Reza","article_published_time":"2020-12-06T18:30:08+00:00","og_image":[{"width":1621,"height":800,"url":"http:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png","type":"image\/png"}],"author":"Reza","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Reza","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/","url":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/","name":"Alamofire URLRequestConvertible - Swift with Reza","isPartOf":{"@id":"https:\/\/mohammadreza.me\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#primaryimage"},"image":{"@id":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#primaryimage"},"thumbnailUrl":"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png","datePublished":"2020-12-06T18:30:08+00:00","author":{"@id":"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c"},"description":"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network...","breadcrumb":{"@id":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#primaryimage","url":"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png","contentUrl":"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/12\/router-pattern-for-alamofire-1.png","width":1621,"height":800,"caption":"URLRequestConvertible"},{"@type":"BreadcrumbList","@id":"https:\/\/mohammadreza.me\/blog\/2020\/12\/06\/urlrequestconvertible\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/mohammadreza.me\/blog\/"},{"@type":"ListItem","position":2,"name":"Router pattern with Alamofire\u2019s URLRequestConvertible protocol"}]},{"@type":"WebSite","@id":"https:\/\/mohammadreza.me\/blog\/#website","url":"https:\/\/mohammadreza.me\/blog\/","name":"Swift with Reza","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/mohammadreza.me\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c","name":"Reza","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g","caption":"Reza"},"sameAs":["http:\/\/mohammadreza.me\/blog"],"url":"https:\/\/mohammadreza.me\/blog\/author\/mohammadreza\/"}]}},"wps_subtitle":"If you are an iOS developer and you\u2019ve been developing for some time, your app probably needs to communicate with API over the network and retrieves data from a server. In this tutorial, we learn about Alamofire router pattern which helps us to have a clean network layer and avoid duplication code.","_links":{"self":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts\/96","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/comments?post=96"}],"version-history":[{"count":0,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts\/96\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/media\/122"}],"wp:attachment":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/media?parent=96"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/categories?post=96"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/tags?post=96"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}