9781839210051 Flipbook PDF


111 downloads 134 Views 10MB Size

Recommend Stories


Porque. PDF Created with deskpdf PDF Writer - Trial ::
Porque tu hogar empieza desde adentro. www.avilainteriores.com PDF Created with deskPDF PDF Writer - Trial :: http://www.docudesk.com Avila Interi

EMPRESAS HEADHUNTERS CHILE PDF
Get Instant Access to eBook Empresas Headhunters Chile PDF at Our Huge Library EMPRESAS HEADHUNTERS CHILE PDF ==> Download: EMPRESAS HEADHUNTERS CHIL

Story Transcript

Xamarin.Forms

Projects

Second Edition Build multiplatform mobile apps and a game from scratch using C# and Visual Studio 2019

Daniel Hindrikes and Johan Karlsson Foreword by David Ortinau Principal Program Manager, Microsoft

FOR SALE IN INDIA ONLY

www.packt.com

Xamarin.Forms Projects Second Edition

Build multiplatform mobile apps and a game from scratch using C# and Visual Studio 2019

Daniel Hindrikes Johan Karlsson

BIRMINGHAM - MUMBAI

Xamarin.Forms Projects Second Edition Copyright © 2020 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Commissioning Editor: Pavan Ramchandani Acquisition Editor: Heramb Bhavsar Content Development Editor: Keagan Carneiro Senior Editor: Sofi Rogers Technical Editor: Shubham Sharma Copy Editor: Safis Editing Project Coordinator: Kinjal Bari Proofreader: Safis Editing Indexer: Manju Arasan Production Designer: Jyoti Chauhan First published: December 2018 Second edition: June 2020 Production reference: 1180620 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-83921-005-1

www.packt.com

I dedicate this book to all the people I met during my years as a Xamarin developer that never believed in Xamarin. If you read this book, you will hopefully understand how great Xamarin is! – Daniel Hindrikes

This book is dedicated to the spider in my basement that motivated me to write a book thick enough to finally kill him with. – Johan Karlsson

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Fully searchable for easy access to vital information Copy and paste, print, and bookmark content Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Foreword Sometimes I scratch my head and wonder why Xamarin.Forms continues to rise in developer satisfaction ratings, winning more fans than ever before in its 6-year history. A developer recently said to me, "It's like you listened to our complaints and requests, and just fixed them." While that's an over-simplified summary, I get what they meant. Our program managers and engineers constantly feed their curiosity to figure out how we can delight those using our software. This has led to a faster build and deploy loop, Hot Reload for instant XAML changes in your running app, and Hot Restart for developing on your iOS device directly from Visual Studio on Windows. Today, Xamarin.Forms ships with more controls "in the box" than ever before, largely thanks to an ever-expanding community of faithful contributors. And what about tomorrow? As I write this, we have just finished Microsoft Build 2020, where we announced our long-term plans for Xamarin.Forms and .NET 6, taking our roadmap all the way into 2022. What a great time to be a Xamarin.Forms and .NET developer! Your investment in .NET for building multi-platform apps will continue to pay off for years to come. In my role at Microsoft on the .NET team, I'm frequently asked by developers where to find guidance to build Xamarin apps just like those presented in this book. I completely understand why! I love to learn by doing, playing, fiddling, and hopefully not banging my head too hard on the keyboard. Daniel and Johan bring many years of experience to this formula, to lead us down the path of success. I recommend this book to you, whether you are new to Xamarin.Forms or a grizzled .NET veteran. You'll find some lessons that are worth your while. David Ortinau Principal Program Manager, .NET Microsoft

Contributors About the authors Daniel Hindrikes is a developer and architect with a passion for developing mobile apps powered by the cloud. Daniel fell in love with Xamarin in the early days of Xamarin when he realized that he could use C# even for iOS and Android apps, and that he could share code with the Windows apps he was also building. But Daniel started to build mobile apps long before that, working on Android apps with Java and even Java ME apps (a long, long time ago). Daniel enjoys sharing his knowledge and can be found speaking at conferences, blogging, or recording the podcast, The Code Behind. Daniel works at the company tretton37 in Sweden and has experience working with both local and global customers. I want to say a special thanks to my family, my wife, Anna-Karin, and our twins, Ella and Willner, all of whom have supported me during the writing process. I also would like to say thanks to the fantastic team at Packt and our technical reviewers, Jimmy and Geoff, who helped us to write this book and make us look better than we really are. Johan Karlsson has been working with Xamarin since the days of MonoTouch and Mono for Android, and it all started with writing a game. He is a full-stack developer, currently focusing on mobile applications using Xamarin, but has in the past worked a lot with ASP.NET MVC, Visual Basic.NET (not proud), and C# in general. Also, he's created a whole bunch of databases in SQL Server over the years. Johan works at tretton37 in Sweden and has about 20 years' experience in the trade of assembling ones and zeros. I want to send a special thanks to my partner in life, Elin. Thanks for being there during this special period of time including (but not limited to) moving together, a pandemic, writing a book, and selling a house. And of course to my children, Ville and Lisa, for being an inspiration in life! Also thanks to Packt and our tech reviewers, Jimmy and Geoff, who nitpicked our applications apart, making us spend late nights correcting our code.

About the reviewers Jimmy Engstrom wrote his first line of code when he was 7 years old, and it has since that day been his greatest passion. It is a passion that has made him the developer he is today and that has taken him around the world, spreading his knowledge. It has earned him awards such as second place in Dice's worldwide game developer competition, a place in the top-ten best developers in Sweden, six Microsoft MVP awards in Windows development, not to mention becoming Geek of the Year. When he is not out spreading his knowledge, he is working as a web developer, trying out the latest tech, or reading up on the latest framework. Jimmy also runs his own company called Azm Dev with his wife, where they focus on "future tech" such as Blazor and holographic computing, but also teaching UX and presentation skills. He is the co-host of a podcast called Coding After Work and also a Twitch channel with the same name. A big thank you to my wife, Jessica, who has been picking up my slack while reviewing this book. Geoff Webber-Cross has over 16 years' software development experience, working in a variety of sectors on Windows, web, and mobile applications. He has worked on XAML/MVVM applications since the days of Silverlight and Windows Phone 7 and has been building Xamarin apps commercially for a number of years. Geoff is also the author of two books for Packt: Learning Microsoft Azure and Learning Windows Azure Mobile Services for Windows 8 and Windows Phone 8.

Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents Preface

1

Chapter 1: Introduction to Xamarin Native applications Xamarin and Mono Code sharing Using existing knowledge

Xamarin platforms Xamarin.iOS Xamarin.Android Xamarin.Mac

Xamarin.Forms

The architecture of Xamarin.Forms Defining a UI using XAML Defining a Label control Creating a page in XAML Creating a page in C# XAML or C#?

Xamarin.Forms versus traditional Xamarin When to use Xamarin.Forms

Setting up a development machine Setting up a Mac

Installing Xcode Installing Visual Studio Configuring the Android emulator

Setting up a Windows machine

Installing Xamarin for Visual Studio Pairing Visual Studio with a Mac Configuring an Android emulator and hardware acceleration Configuring UWP developer mode

Xamarin productivity tooling Xamarin Hot Restart Xamarin XAML Hot Reload

Summary Chapter 2: Building Our First Xamarin.Forms App Technical requirements An overview of the project Beginning the project Setting up the project

Creating the new project

7 8 8 9 10 10 10 11 12 12 13 14 14 15 16 16 17 18 18 19 19 19 20 24 24 26 27 33 34 34 34 35 37 38 38 38 38 39

Table of Contents

Examining the files DoToo DoToo.Android DoToo.iOS DoToo.UWP

Updating the Xamarin.Forms packages Removing the MainPage file

Creating a repository and a TodoItem model Defining a to-do list item Creating a repository and its interface Connecting SQLite to persist data

Adding the SQLite NuGet package Updating the TodoItem class Creating a connection to the SQLite database Implementing the GetItems(), AddItems(), and UpdateItems() methods

Using MVVM – creating views and ViewModel

Defining a ViewModel base class Introducing PropertyChanged.Fody Creating the MainViewModel Creating the TodoItemViewModel Creating the ItemViewModel class Creating the MainView view Creating the ItemView view Wiring up a dependency injection through Autofac Adding a reference to Autofac Creating the resolver Creating the bootstrapper Adding a bootstrapper on iOS Adding a bootstrapper in Android Adding a bootstrapper in UWP

Making the app run

Adding data bindings

Navigating from MainView to ItemView to add a new item Adding new items to the list Binding ListView in MainView Creating a ValueConverter object for the item status Using ValueConverter

Navigating to an item using a command Marking an item as complete using a command Creating the filter toggle function using a command

Laying out the contents

Setting an application-wide background color Laying out the MainView and ListView items The filter button Touching up ListView

Summary Chapter 3: Building a News App Using Xamarin.Forms Shell Technical requirements Project overview Getting started [ ii ]

42 44 45 46 47 48 49 50 50 51 53 53 55 55 57 58 59 60 61 62 63 64 67 69 69 70 71 73 74 74 75 76 77 78 80 83 85 86 88 89 91 92 92 93 93 94

95 96 96 96

Table of Contents

Building the news app Setting up the project

Creating the new project Updating Xamarin.Forms packages

Creating the structure of the app

Creating the ViewModel base class

Recapping on Quick PropertyChanged.Fody Implementing INotifyPropertyChanged Adding a reference to PropertyChanged.Fody Creating a FodyWeaver file

Creating the HeadlinesViewModel class Creating the HeadlinesView Creating the ArticleItem Creating the ArticleView Creating the AboutView Wiring up dependency injection through Autofac Adding a reference to Autofac Creating the resolver Creating the bootstrapper Initializing the bootstrapper

Downloading and configuring Font Awesome

Downloading Font Awesome Adding Font Awesome to Info.plist on iOS Adding the font to a static resource Defining some icons in the resource dictionary

Defining the shell

Creating the MainShell file Defining the basic structure Adding the MainShell type to the container

Making the app run

Creating the news service Obtaining an API key Creating the models Creating a service class

Creating the NewsScope enum Enabling C# 8 Creating the NewsService class

Wiring up the NewsService class

Extending the HeadlinesViewModel class Extending the HeadlinesView Extending the ContentView of the ArticleItem Adding to the bootstrapper Adding a ContentTemplate attribute

Handling navigation

Creating the navigation service

Creating the INavigation interface Implementing the INavigation interface using Shell Adding the INavigation interface to the ViewModel class

Navigating using routes

Finalizing the ItemSelected command Extending the ArticleView to receive query data Extending the ArticleView with a WebView

[ iii ]

96 96 97 100 102 102 103 103 104 104 105 105 107 108 109 110 110 111 112 113 114 114 114 115 116 117 118 119 121 122 122 123 125 126 126 127 128 130 130 132 134 136 137 139 139 139 140 141 141 142 142 144

Table of Contents Registering the route

Summary Chapter 4: A Matchmaking App with a Rich UX Using Animations Technical requirements Project overview Creating the matchmaking app Creating the project

Creating the new project Updating the Xamarin.Forms NuGet packages

Designing the MainPage file Creating the Swiper control

Creating the control Defining the main grid Adding a content view for the photo Creating the DescriptionGenerator class Creating a picture class Binding the picture to the control Setting the source Controlling the loading label

Handling pan gestures

Testing the control Creating decision zones Extending the grid

Adding the StackLayout for liking photos Adding the StackLayout for denying photos

Determining the screen size Adding a clamp function Adding code to calculate the state

Defining a method for calculating the state Wiring up the pan state check

Adding exit logic

Checking if the image should exit Removing the image Updating PanCompleted

Adding events to the control Declaring two events Raising the events

Wiring up the Swiper control Adding images

Adding initial photos Making the call from the constructor

Adding count labels Subscribing to events

Adding methods to update the GUI and respond to events Wiring up events

Summary Chapter 5: Building a Photo Gallery App Using CollectionView and CarouselView [ iv ]

144 145 147 148 148 148 148 149 151 153 154 155 156 157 159 160 161 161 162 162 166 167 167 167 168 168 170 170 170 171 172 172 173 174 174 175 175 176 176 176 177 177 178 178 179 180 181

Table of Contents

Technical requirements Project overview Building the photo gallery app Importing photos

Importing photos from the iOS photo gallery Importing photos from the Android photo gallery

Writing the app-initializing code

Creating a shell Creating a base view model Creating a bootstrapper and a resolver Creating the bootstrapper

Creating the gallery view

Creating the ViewModel Creating the view Loading photos incrementally Saving favorites

Creating the carousels

Creating the view model for the favorite photos Creating the view model for the latest photos Showing the favorites photos

Summary Chapter 6: Building a Location Tracking App Using GPS and Maps Technical requirements Project overview Building the MeTracker app Creating a repository to save the locations of our users Creating a model for the location data Creating the repository

Xamarin.Essentials Creating a service for location tracking Setting up the app logic Creating a view with a map Creating a ViewModel Creating a resolver Creating the bootstrapper

Creating the iOS bootstrapper Creating the Android bootstrapper

Setting the MainPage

Background location tracking on iOS

Enabling location updates in the background Getting permissions to use the location of the user Subscribing to location updates

Background location tracking with Android

Adding the required permissions to use the location of the user Creating a background job Scheduling a background job Subscribing to location updates

[v]

181 182 182 184 185 189 194 194 195 196 197 200 201 202 204 205 209 209 210 211 212 213 213 214 214 216 216 217 219 219 220 220 224 227 228 230 231 232 233 233 234 234 237 238 239 240 241

Table of Contents

Creating a heat map

Adding the GetAll method to LocationRepository Preparing the data for visualization Creating custom renderers

Creating a custom control for the map Creating a custom renderer to extend the map in the iOS app Creating a custom renderer to extend the map in the Android app

Refreshing the map when resuming the app

Summary Chapter 7: Building a Weather App for Multiple Form Factors Technical requirements Project overview Building the weather app Creating models for the weather data

Adding the weather API models manually Adding the app-specific models Adding the ForecastItem model Adding the Forecast model

Creating a service to fetch the weather data Configuring the applications so they use location services

Configuring the iOS app so that it uses location services Configuring the Android app so that it uses location services Configuring the UWP app so that it uses location services

Creating the ViewModel class Getting the weather data Grouping the weather data

Creating a Resolver Creating a bootstrapper Creating the view for tablets and desktop computers Using FlexLayout Adding a toolbar item to refresh the weather data Adding a loading indicator

Setting a background image

Creating the view for phones

Using a grouped CollectionView Adding pull to refresh functionality

Navigating to different views based on the form factor Handling states with VisualStateManager Creating a behavior to set state changes

Summary Chapter 8: Setting Up a Backend for a Chat App Using Azure Services Technical requirements Understanding the different Azure serverless services Azure SignalR Service Azure Functions Azure Blob storage

[ vi ]

243 244 244 249 249 251 254 257 258 259 259 260 260 260 261 262 263 263 264 268 268 268 270 270 272 273 276 277 278 279 282 283 284 285 286 288 289 292 294 298 299 300 300 300 301 302

Table of Contents

Azure Cognitive Services

302 303 304 Creating a SignalR service 304 Creating a storage account 305 Creating an Azure Cognitive Service 308 Using Azure Functions as an API 308 Creating the Azure service for functions 309 Creating a function to return the connection information for the SignalR service 311 Creating a message library 314 Creating a storage helper 316 Creating a function for sending messages 320 Using the Computer Vision API to scan photos for adult content 322 Creating a scheduled job to clear photos from storage 324 Deploying the functions to Azure 326 Summary 327

Project overview Building the serverless backend

Chapter 9: Building a Real-Time Chat Application Technical requirements Project overview Getting started Building the chat app Creating the chat service Initializing the app

Creating a resolver Creating a Bootstrapper

Creating a base ViewModel Creating the main view Creating MainViewModel Creating MainView

Replacing MainPage Editing the XAML Fixing the code behind the view

Setting the main view

Creating ChatView

Creating ChatViewModel

Creating the class Adding the text property Receiving messages Creating the LocalSimpleTextMessage class Sending text messages Installing the Acr.UserDialogs plugin Installing the Media plugin Sending photos

Creating the ChatView

Creating Base64ToImageConverter Creating the skeleton ChatView Adding ResourceDictionary Adding CollectionView

[ vii ]

329 329 330 330 330 331 338 338 339 341 342 342 343 343 344 345 346 347 347 347 350 350 352 352 354 354 355 358 358 360 362 362

Xamarin.Forms Projects – Second Edition Xamarin.Forms is a lightweight cross-platform development toolkit for building apps with a rich user interface. Improved and updated to cover the latest features of Xamarin.Forms, this second edition covers CollectionView and Shell, along with interesting concepts such as augmented reality (AR) and machine learning. Starting with an introduction to Xamarin and how it works, this book shares tips for choosing the type of development environment you should strive for when planning cross-platform mobile apps. You’ll build your first Xamarin.Forms app and learn how to use Shell to implement the app architecture. The book gradually increases the level of complexity of the projects, guiding

you through creating apps ranging from a location tracker and weather map to an AR game and face recognition. As you advance, the book will take you through modern mobile development frameworks such as SQLite, .NET Core Mono, ARKit, and ARCore. You’ll be able to customize your apps for both Android and iOS platforms to achieve nativelike performance and speed. The book is filled with engaging examples, so you can grasp essential concepts by writing code instead of reading through endless theory. By the end of this book, you’ll be ready to develop your own native apps with Xamarin. Forms and its associated technologies, such as .NET Core, Visual Studio 2019, and C#.

Things you will learn: •

Set up Xamarin.Forms to build native apps with code-sharing capabilities



Use Azure SignalR to implement serverless services in your Xamarin apps



Understand the core aspects of developing a mobile app, such as its layout, UX, and rendering



Create an AR game for Android and iOS using ARCore and ARKit, respectively



Use custom renderers to gain platform-specific access





Discover how to create custom layouts for your apps with Xamarin.Forms Shell

Build and train machine learning models using CoreML, TensorFlow, and Azure Cognitive Services

www.packt.com

FOR SALE IN INDIA ONLY

Get in touch

Social

© Copyright 2013 - 2024 MYDOKUMENT.COM - All rights reserved.