Writing iOS apps with Xamarin and Visual Studio

Source: Internet
Author: User
Tags call back dashed line set background uikit

Original: Building IOS Apps with Xamarin and Visual Studio
(Bill Morefield] (Https://www.raywenderlich.com/u/bmorefield)
Translator: Kmyhy

If you develop an IOS app, you'll immediately think of Apple's development language Objective C/swift and Xcode. However, this is not the only option, and we can use other languages and frameworks entirely.

One of the main alternatives is Xamarin, a cross-platform framework that allows you to develop IOS, Android and OSX, Windows apps, which use C # and Visual Studio. The biggest benefit is that Xamarin allows you to share code between IOS and Android apps.

Xamarin has one of the biggest benefits compared to other cross-platform frameworks: Using Xamarin, your project compiles native code and uses local APIs. That said, apps written with Xamarin are no different than those made with Xcode. For more details, please read this article Xamarin vs. Native App development.

But Xamarin has a big drawback, that is, its price. The $1000/year price per platform may be enough to give you the ability to quit the latte or buccino you drink every day ... It is dangerous for programmers not to drink coffee. Because of the high price, Xamarin has so far only been used in a budget-rich corporate project.

But that has changed since Microsoft acquired Xamarin, and Microsoft has integrated it into the new version of Visual Studio, even the free community edition. The Community edition is free for individual developers and small teams.

Free? That's very kind of you!

In addition to the price (or regardless of price), Xamarin has other benefits, including allowing programmers to:

    • Write mobile apps using legacy C # libraries and tools.
    • Share code between apps on different platforms.
    • Share code between the ASP. NET background and front-end apps.

Xamarin also allows you to change the tools according to your needs. If you want to maximize cross-platform sharing of code, use Xamarin Forms, which is ideal for apps that are not specific to a particular platform or that require a separate UI customization.

If your app needs to invoke a particular platform-specific feature or interface, use the Xamarin.ios, xamarin.android, or other platform's modules so you can invoke the local API and framework directly. These modules are able to create highly customized UIS while supporting cross-platform on common code.

In this tutorial, you'll use Xamarin.ios to create an IPhone app that lists the user's photo gallery.

This tutorial does not require any IOS or Xamarin development experience, but it is best to have a C # foundation.

Begin

To develop an IOS app with Xamarin and Visual Studio, ideally you need two computers:

    • A Windows computer that runs Visual Studio and writes code.
    • A MAC computer with Xcode to act as a buid host. It is not specifically used for compiling, but is used during development and debugging to accept network requests from Windows computers.

The closer the physical distance between the two computers, the better, because when you compile and run on a Windows PC, the IOS emulator runs on your MAC computer.

You might ask, "What if I don't have two computers?" ”

    • For users who only use the Mac platform, Xamarin also provides the IDE under OSX, but the main purpose of this tutorial is to demonstrate the new Visual Studio. If you don't like this, you can run a Windows virtual machine on your Mac. VMWare fushion or free open source VirtualBox are available.

      If you use a Windows virtual machine, you need to ensure that Windows can access your MAC over the network. In other words, you need to Ping the IP address of your Mac under Windows.

    • For pure Windows users, buy a Mac now and then. I'll be right here waiting for you! If not, use a cloud service like Macincloud or Macminicolo.

This tutorial assumes that you have a separate Mac and Windows PC, and of course, this tutorial is also useful for people who use Windows hosts under their Mac.

Installing Xcode and Xamarin

Download and install Xcode on your Mac computer if you haven't done so yet. This is no different from installing other apps from the App Store, but it's a few grams large and takes a little longer.

After you have installed Xcode, download Xamarin Studio to your Mac computer. Do not fill in the email address, download is free of charge. Do you think it's cool--it doesn't have to cost you any kind of coffee!

After the download is complete, open the installation package and double-click Install Xamarin.app. To receive the terms of the agreement, click Continue.

The installer will automatically find the installed tools and check the current operating system version. It will display a list of development environments. Tick the Xamarin.ios and click Continue.

You will then see a confirmation list that lists what will be installed. Click Continue. You will then see an overview, as well as an option to start Xamarin Studio. Direct point Quit to complete the installation.

Install Visual Studio and Xamarin

In this tutorial, you can use any version of Visual Studio, even the free community edition. The Community edition is not completely functional, but it does not affect your ability to develop complex apps at all.

Your Windows when you have to meet the minimum system requirements of Visual Studio. For a smoother development experience, you need at least 3 GB of memory.

If you have not installed Visual Studio, you can download the community version of the installer by tapping the Green Community Edition 2015 button from the Community page.

Run the installer, start the installation, and select the Custom installation option. In the list of features, expand cross-platform phone development, and then choose C#/.net (Xamarin v4.0.3) (the version that is written at this tutorial is likely to be different).

Click Next and wait for the installation to complete. Time is a bit long, you can stand up and walk and digest the biscuits you ate when installing Xcode:]

If you have already installed Visual Studio but do not have Xamarin tools, go to Windows Programs and Features, locate Visual Studio 2015, select it, click Change, and then select Modify 。

Under cross Platform Mobile development Find Xamarin, C#/.net (Xamarin v4.0.3), tick it and click Upate to install.

It's a lot of stuff, but it's finally done!

Write Apps

Open Visual Studio and select File\new\project. Under Visual C #, expand IOS and select the single View App template for IPhone. This template creates a App,view controller with only one view controller that is the class for managing views in the IOS app.

Enter imagelocation, either name or solution name. Select the project save path, then click OK, and the new project will be created.

Visual Studio will prompt you to specify a MAC computer as the BUiD host for Xamarin:

    1. On your MAC computer, open System Preferences and select Share.
    2. Open Telnet.
    3. Change allow access to only these users, and then add the users that will be used to access Xamarin and Xcode on your Mac.

    4. Close the window and return to the Windows computer.

Go back to Visual Studio, select your Mac computer when you are asked to designate a Mac as the build host, and then click Connect. Enter your username and password and click Login.

You can check the toolbar to see if the connection is successful.

Select IPhone Simulator from the Solution Platform drop-down box, which will automatically select a simulator for the build host. If you want to change to another emulator, you can click the small arrow to the right of the current emulator.

Press the green Debug arrow or the F5 shortcut key to compile and run the program.

Once the compilation is complete, you can't see any effect on Windows. Because it runs on your MAC (build host). That's why it's best to put two machines as close as possible!

At the Evolve conference a few days ago, Xamarin announced that it would launch IOS Simulator Remoting, which would allow you to interact with apps running on the Apple IOS emulator, just like running an emulator on a Windows PC. But at the moment, you still need to deal with the simulator running on your MAC.

On the emulator, you will see a splash screen flash and then display an empty window. Congratulations to you! Your Xamarin will work properly.

To stop the app, you can click the Red Stop button (Shift+f5 shortcut).

Create Collection View

This app will show the user a Collection view to show the thumbnail images in the user's album. Collection View is an IOS control that displays multiple entries in a grid format.

To edit scenes in the app storyboard, open Main.storyboard from Solution Manager.

In the Search bar in the toolbox, enter the collection typeface to filter. Drag the Collection view below the Data view to the center of the empty view.

Select Collection View and you'll see some small, hollow circles around it. If you see a T-word instead of a small circle, click it again to switch to the small circle.

Click and drag each small circle until you see the Blue Line and release the mouse button, and the edge of the control is automatically aligned to the place where the line is located.

Then set the automatic layout constraint for Collection view, which is used to tell the app how the view should resize when the device spins the screen. In the toolbar on the top of the storyboard, click the Green Plus button to the right of the CONSTRAINTS typeface. This will automatically create a constraint for Collection View.

The automatically created constraints are mostly correct, but some of them need to be adjusted. In the Properties window, switch to the Layout tab and pull to the Constraints column.

The two constraints in the margin are correct, but the width-height constraints are incorrect. Remove the Width and Height constraints (click the X button to their right).

Notice that the Collection View turns orange at this point. This indicates that the constraint is incorrect.

Click Collection view to select it. If you see the same circle as before, click it once to switch to the green T-word icon. Click and drag the T-word at the Top of the Collection View until the green name is the outer border of the upper Layout Guide. Release the left mouse button, which creates a constraint relative to the top of the view.

Then, click and drag the T-word to the left of Collection View until you see a blue dashed line. Release the left mouse button, which creates a constraint relative to the left edge of the view.

At this point, your constraint should be this:

Configure Collection View Cell

Do you see the small squares in Collection View? There is a red exclamation mark in this block. This is a Collection view cell, which represents a cell in the Collection view.

To configure the size of this cell, you need to do so in Collection View. With Collection View selected, pull up to the top of the Layout tab. In the Cell Size section, set its Width and Height to 100.

Then, click the red exclamation point in the Collection View Cell, which pops up a prompt window that says you haven't assigned a reuse identifier to the cell. So, select the cell, open the Widget tab, drop down to the Collection reusable View section, and set the Identifier to Imagecellidentifier. This will make the error disappear.

Continue to drop down and come to Interaction, set Background color to blue in predefined.

Now, the scene effect becomes:

Pull up to the top of the Widget section and set Class to Photocollectionimagecell.

Visual Studio automatically creates classes of the same class name, inherits Uicollectionviewcell, and automatically creates a PhotoCollectionImageCell.cs file. Alas, when will Xcode be the same as Visual Studio?!

Create a Colleciton View data source

You also need to create a class that acts as a uicollectionviewdatasource to provide data for Collection View.

Right-click on the imagelocation of the Solution Manager, select Add \ class, class name PhotoCollectionDataSource.cs and click Add.

Open the newly created PhotoCollectionDataSource.cs, and then write to the top of the file:

using UIKit;

This will import the IOS UIKit framework.

Then the class definition:

publicclass PhotoCollectionDataSource : UICollectionViewDataSource{}

Remember the reuse identifier you defined for Collection View Cell? We're going to use it here. In the class definition, add:

privatestaticreadonlystring"ImageCellIdentifier";

There are two abstract methods in the Uicollectionviewdatasource class that must be implemented. In the class, add:

publicoverrideGetCell(UICollectionView collectionView,     NSIndexPath indexPath){    var imageCell = collectionView.DequeueReusableCell(photoCellIdentifier, indexPath)       as PhotoCollectionImageCell;    return imageCell;}publicoverrideGetItemsCount(UICollectionView collectionView, nint section){    return7;}

The Getcell () method is responsible for providing a cell for display in Collection View.

The Dequeuereusablecell method reuses cells that are no longer in use, such as cells that do not already have to be displayed on the screen, and then return to that cell. If there are no reusable cells, a new cell is created.

The Getitemscount method is responsible for telling Collection View how many (7) cells to display.

Then you need to add a reference to the Collection view in the Viewcontroller class, Viewcontroller is the Scene that manages the Collection view. Go back to Main.storyboard, select Collection View, come to the Widget tab, and set Name to CollectionView.

Visual Studio automatically creates an instance variable named CollectionView in the Viewcontroller class.

Note that you cannot see this instance variable in ViewController.cs. To see this variable, you need to click on the right arrow to the left of ViewController.cs to open ViewController.designer.cs. This is where you can see the instance variables that Visual Studio created for you.

Open ViewController.cs from Solution Manager and add the following fields to the class:

private PhotoCollectionDataSource photoDataSource;

At the end of Viewdidload (), add code to initialize the data source and bind it to the Collection View:

photoDataSource = new PhotoCollectionDataSource();collectionView.DataSource = photoDataSource;

In this way, Photodatasource can provide data for Collection View.

Compile and run the program. You will see the Collection view showing 7 blue squares.

Great-everything goes well!

Show Photos

The blue squares are done, and the next step is to turn the data sources into pictures taken from the device and display them in Collection View. You'll use the Photos framework to access photos and videos from the Photos app.

Next, you need to add an Image View to the cell. Open Main.stroyboard and select Collection View Cell. In the Widget tab, drop down and set Background Color as default.

In the toolbox, search for Image view, and then drag an image view into the cell.

The default size of Image view is larger than cell, to modify its size, select the image view and then, under the View section of the Properties \ Layout tab, set X and Y to 0, Width and Height to 100.

Switch to the Widget tab and set Name to Cellimageview. Visual Studio automatically creates a variable named Cellimageview.

Pull to the View bar and set Mode to Aspect Fill. This will prevent the picture from being scaled.

Note: You cannot see the Cellimageview variable in PhotoCollectionImageCell.cs. This class is partial, and this variable is in a different file.
In Solution Manager, click the arrow to the left of PhotoCollectionImageCell.cs to expand it. Open PhotoCollectionImageCell.designer.cs and you will see the Cellimageview variable declaration.

This file is created automatically, do not change it. Otherwise, they will be overwritten without your knowledge or cause the binding between the class and the storyboard to be interrupted, resulting in a run-time error.

This variable is not public, so other classes cannot access it. Therefore, you need to provide a way to access it so that we can change the image displayed on the image view.

Open PhotoCollectionImageCell.cs Add the following method:

publicvoidSetImage(UIImage image){    cellImageView.Image = image;}

Now you can get photocollectiondatasource to grab the photos.

At the top of the PhotoCollectionDataSource.cs:

using Photos;

Add Variables in Photocollectiondatasource:

private PHFetchResult imageFetchResult;private PHImageManager imageManager;

The Imagefetchresult variable stores an array of photos corresponding to Asset, and then obtains the photo data from the Imagemanager object.
Before the Getcell () method, add a constructor method:

publicPhotoCollectionDataSource(){    null);    new PHImageManager();}

This construction method fetches all the picture resources from the Photos app and puts the results into the Imagefetchresult variable. It then initializes imagemanager,app to use it to query the specific data for each picture.

Below the constructor method, add a destructor to release the Imagemanager object:

~PhotoCollectionDataSource(){    imageManager.Dispose();}

Replace the original empty cell with the picture from the new data source in the Getitemscount and Getcell methods. Modify the Getitemscount () method to:

publicoverrideGetItemsCount(UICollectionView collectionView, nint section){    return imageFetchResult.Count;}

Modify the Getcell method to:

 Public OverrideUicollectionviewcellGetcell(Uicollectionview CollectionView, Nsindexpath Indexpath) {varImagecell = Collectionview.dequeuereusablecell (Photocellidentifier, Indexpath) asPhotocollectionimagecell;//1    varImageasset = Imagefetchresult[indexpath.item] asPhasset;//2Imagemanager.requestimageforasset (Imageasset,NewCoregraphics.cgsize (100.0,100.0), Phimagecontentmode.aspectfill,NewPhimagerequestoptions (),//3(UIImage image, nsdictionary info) = {//4Imagecell.setimage (image); });returnImagecell;}

The above code is described separately as follows:

    1. Indexpath indicates which cell is currently returned. Its Item property represents the index of the cell. We get the image resource and convert it to a Phasset object based on this index.
    2. Use the Imagemanager object to request a picture of the Phasset, specifying the size and zoom mode of the desired picture.
    3. Many methods in the IOS framework use deferred execution when a time-consuming task is performed, and then call the delegate method when the task is complete. In the case of the Requestimageforasset method, when the request is complete, the delegate method is called, and the requested picture and related information is passed to the delegate method via parameters.
    4. Finally, set the picture in the cell.

Compile and run. You will be asked for permission to access.

If you choose Ok,app nothing will show. Oh, screw it!

IOS believes that photos belong to the user's sensitive information and needs to be authorized by the user. However, when the user agrees to authorize, the app must also register to receive the appropriate notification to refresh the view again. That's your next job.

Sign up for photo access authorization notifications

First, you need to add a method to the Photocollectiondatasource class to re-fetch the data when the photo library content changes. Add the following methods to the class:

publicvoidReloadPhotos(){    null);}

Then, open ViewController.cs to import the photos framework:

using Photos;

In the Viewdidload () method:

//1PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver((changeObserver) =>{    //2    InvokeOnMainThread(() =>    {        // 3        photoDataSource.ReloadPhotos();        collectionView.ReloadData();    });});

The code above is responsible for:

    1. Register the app to receive photo gallery change notifications and invoke the specified code when the photo gallery content changes.
    2. The Invokeonmainthread () method refreshes the UI in the main thread, or it causes the app to crash.
    3. Call Photodatasource.reloadphotos () to retrieve the photo, call Collectionview.reloaddata () and let Collection View redraw.

Finally, let's resolve the previous issue, requesting authorization from the user when the app has not yet been granted access to the album.

In the Viewdidload () method, join before initializing the Photodatasource:

if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.NotDetermined){    PHPhotoLibrary.RequestAuthorization((PHAuthorizationStatus newStatus) =>    { });}

The current authorization status needs to be checked, and if the user is not authorized, the user is prompted for authorization.
In order to prompt the user for authorization again, you need to reset the emulator via Simulator \ Reset Content and Settings.

Compile and run. You'll see a photo access authorization prompt, and if you choose OK, the app will show the thumbnail of the photo in Collection View!

Conclusion

You can download the full Visual Studio project from here.

In this tutorial, you learned how to configure Xamarin and how to use it to create an IOS app.

There are several excellent learning resources on the Xamarin Guide website. To learn more about creating cross-platform apps, see the Xamarin tutorial about creating the same app for IOS and Android apps.

Microsoft's acquisition of Xamarin has made some impressive changes. You'll see this tendency in Microsoft's Build call back and Xamarin Evolve. Xamarin has released a video of recent Evolve conferences that detail information about how to use Xamarin and future product directions.

Do you use Xamarin to create apps? If you have any questions or suggestions for this article, please leave a comment below.

Writing iOS apps with Xamarin and Visual Studio

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.