How do I build an app like Instagram with Parse and Swift?

Source: Internet
Author: User
Tags install cocoapods

"Editor's note" the author of this article is Reinder de Vries, an entrepreneur and an excellent programmer, who publishes multiple application blogs. In this article, the author focuses on how to create an Instagram-like app based on the parse feature, complete and clear steps that provide a great learning experience for developers. This article is compiled and collated by OneAPM engineers.

The parse is a mobile application development platform with a very interesting product: the parse Core. One of its features is to allow app developers to store data directly in the cloud without worrying about setting up a server or re-designing a REST API. The Parse core is a local backup (such as core data), which makes it easy to solve the offline and offline backend problems.

This tutorial focuses on creating a Parse-based application. We'll build an app like Instagram that includes the following features:

    1. Loading data from Parse, stored locally;
    2. Save data to Parse and write back to the cloud;
    3. Like the pictures of Cat.

This app will be developed entirely in swift language, and Swift is Apple's newest programming language for IOS apps. Parse does not use the full rewrite of Swift, so we need to create a bridge connector to handle both compatibility.

Through this article you will learn the following skills:

  • Using Parse to retrieve and store data to the cloud;
  • Cocoapods integrates a Swfit program that invokes the OBJECTIVE-C framework;
  • Build views and custom table view units with interfaces;
  • From scratch, write a complete App with Swift;
  • Use automatic layout and constraints;
  • Use gesture recognition, optional types, conditions, closures, attributes, exits, and actions.
Let's get started!

First, you have to have a Parse account. This can be registered in parse.com via your Facebook, Google +, GitHub account or mail.
Then, log in to Parse, and through Https://www.parse.com/apps you can go to your apps Dashboard.

Create a new application by tapping the "Create new App" button, and enter "paws" as the app name. Next, open the new app and make sure you can see the Core tab.

Creating a data store

Technically, Parse is just an online database. The data is stored as an object with a name and multiple fields, such as a spreadsheet. Such an object is called a class, and its function is the blueprint of the data structure. We're going to use a class named Cat.

On the Core tab, click the button to add a class. In the drop-down box, select Custom, and then type the name of the class: Cat. Then, click Create Class.

In this way, we create a new class, and then we can add a series of standard fields, such as ObjectId, Createdat, Updatedat, and ACLs.

+Colturn the button to the top, adding the following fields, names, and types:

    • Name:name, type:string.
    • Votes, type number.
    • A URL, type String.
    • cc_by, type String.

These fields will provide basic information for the Cat database.

Import data

Now that we've set up the infrastructure, we're ready to import the data! Save the file to: Cat.json.
Then, go back to the Core tab and the database and left click on the "Import" button. Select the file you just saved and upload it. Make sure that the category set is "Custom" and renamed to Cat (not rs1_cat). Then click Finish Import. If the import is complete, Parse will prompt you in a timely manner. Click "got it" and reload the page.
If all goes well, you should now be able to see that there are 10 of Cat in the database. They all have a name, a URL, some votes, and some space reserved for the principle.

At this point, all of our work in Parse has been completed. Start building the Swift Xcode program below.

Build Xcode

Open Xcode and create a new project, select menu → new → project from the start screen.
Select the app for the single view of the category "ios→ app template. Enter the following fields on the next screen:

    • Products name £ º Paws
    • Structure Name: Casual
    • struct identifier: arbitrary, such as Com.appcoda
    • Language: Swift
    • Equipment: Universal

Click Next, select the Project Catalog folder, and then click Create.

We're not going to use storyboards, so click on the Paws, 2 targets, IOS SDK on the top left to open the project settings. In the list on the left, click Paws under Target, and then find the main interface settings for the main area of the screen. Remove the textmain from the box.

Add the Parse library to the Xcode project with Cocoapods

Before you use Parse in your program code, we must add it to the dependency relationship. So we chose Cocoapods, which is a package manager. Many application projects rely on third-party libraries, such as Parse. CocoaPods is a convenient tool for loading libraries and ensures that they are updated in real time.
Perform the following command on the terminal to install Cocoapods. It will ask you to enter your MAC user password. It is not allowed to include the "$" symbol. This flag means the shell command!

$ sudo gem install cocoapods

Halfway if there is no progress in two minutes, there is no need to worry because Cocoapods is being installed. After installation you can see a bunch of lines and finally ... Installation is complete.

Next, create an empty file under the root of the Xcode project and call the Podfile file. Open with your favorite text editor and paste the following code into the file:

pod ‘Parse’, ‘~> 1.7.1′pod ‘ParseUI’, ‘~> 1.1.3′

Podfile will tell Cocoapods which libraries we need. In this case, the Parse version is 1.7.1, and the Parseui version is 1.1.3.
Now, close Xcode and use the terminal to locate the root directory of the program project. Write to the terminal CD, and then locate it in the Paws directory and drag it to the terminal.

Next, enter the following code at the command line:

$ pod install

CocoaPods will look for Podfile and try to install the dependencies we set up. This step will probably take a few minutes. The result should be this:

CocoaPods has downloaded and compiled the Parse and added it to a new workspace. From now on, we are no longer using the original app project, and we will use the workspace created by CocoaPods. It contains our original project and the CocoaPods project.

Note here: Search Browse to find the root directory of the program, open the new workspace in Xcode, and then open the Paws.xcworkspace. Verify the navigation items under the left side, and you will see: Pods and Paws.

Before we write the application directly, we need to establish a connection between Parse and the project. The Parse is built with Objective-c, and our project is in Swift language, which requires proper setup to be compatible.

Using OBJECTIVE-C in Swift projects

Any objective-c library, project, or class can be set up to be compatible with Swift by setting up a bridge connector. Technically, such bridging transforms the objective-c header file into the Swift language.

To create a bridge connector you need to do the following:

1. Add a new file in the Paws directory, select the Paws directory under the Paws project, right-click, and then click New File.
2. Select the Objective-c file template from the "ios→ source category and click Next.
3. Name the class "paws" (or any other name you like), and then proceed and save the file. When prompted, click Yes to configure the Objective-c Bridge Connector.

Xcode creates two new files: PAWS.M and Paws-bridging-header.h. PAWS.M file is useless, you can delete it directly. Write the following code in the Paws-bridging-header.h file:

#import <Parse/Parse.h>#import <ParseUI/ParseUI.h>#import <Bolts/Bolts.h>

See here, you can not help but ask is this a lot of work just to build a programming project? Don't worry, we'll have something interesting to do next. Remember: Parse provides an off-the-shelf online backend that can save a lot of time!

Verify how the Parse works

Return to the Dashboard of parse by Https://parse.com/apps. Hover over the upper-right corner of your account name, click Account, and then click the top bar of the Apply Key tab. You can also access Https://parse.com/account/keys directly.
After you determine the application's Parse Network service, the page displays your app key. The application key consists of a string of alphanumeric or character, basically this is the application password, pay attention to secrecy.
Next, open the file Appdelegate.swift in Xcode. Locate the application's Didfinishlaunchingwithoptions method.
Add the following code to the method, making sure it is on the first line of the method. The whole is this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool  {    Parse.setApplicationId("...", clientKey: "...")return true  }

Replace "..." with the application key of Parse

    1. First, App ID
    2. Second, the client key

After that, try to run the application:

1. Make sure you select the right device, and PLAY Make sure the device is selected, such as IPhone or IPhone6, by confirming the top right of the button.
2. Then, click the Play button or press Command-r to run the program.

The project has no errors during construction and operation. Once run, you can see that the IPhone will appear with a black window, but there is nothing on the window-this is because we removed the main page script and there is no replacement.
Happily: You have successfully configured your project with Parse and CocoaPods!

Create a Table View Controller

To show the Cat pictures in the Paws application, we need to use a table view controller. This is a very common IOS interface component that can display rows of data in a vertical list. The obvious example is the vertical list of people and numbers in the Contacts app on the IPhone. In Objective-c and Swift, a table view controller itself is the Uitableviewcontroller class.

Note: Unfamiliar terminology classes? Use it as a prototype, which is the mold you used in the iron castings. You pour the iron into the mold and you come out with a copy. This replication is referred to as an instance of the class.

Parse has a great correspondence called Parseui, which is a collection of UI elements that can be closely integrated with the parse product. We're going to use the Pfquerytableviewcontroller class. It extends the functionality of the Uitableviewcontroller class with the Parse data. It's a perfect combination.
Create a new Swift class named Catstableviewcontroller. In the project browser, right-click the Paws directory and select New file. From "ios→ source, select the Cocoa Touch class template. Enter the following settings:

    • Class: Catstableviewcontroller
    • Inheritance: Pfquerytableviewcontrolle
    • Language: Swift
    • Make sure the Create XIB file is unchecked

Save the file to the Paws directory. When selecting a directory, make sure that Paws is selected as the target.

Open the new class file, you can see the basic structure: one named Viewdidload, and the other named Didreceivememorywarning. It is important to note that the Catstableviewcontroller extension Pfquerytableviewcontroller is its subclass. In turn, the Pfquerytableviewcontroller class is an extension of uitableviewcontroller, so our table View controller inherits all of the table view features, while adding code and functionality Parseui.

Coded Table View Controller

First, we must override the constructor method of the class to configure the underlying settings.

Add the following two methods to the top of the class, after the first curly brace of the file:

override init(style: UITableViewStyle, className: String!)  {    super.init(style: style, className: className)    self.pullToRefreshEnabled = true     self.paginationEnabled = false      self.objectsPerPage = 25    self.parseClassName = className  }required init(coder aDecoder:NSCoder)  {    fatalError("NSCoding not supported")  }

You have just added two methods:

    • Specifies init initialization, which requires two parameters: the style of the table view and the Parse class name we want to use (here is C)
    • Required initialization, a parameter is required: an instance of Nscoder. So far, its content is irrelevant, stick to it, but don't ask you to use the method creatively.

In the initial initialization, the following items were completed:

1. When Super.init () is called, initializes the parent class Pfquerytableviewcontroller, which completes its own initialization.
2. Next, Pulltorefreshenabled is set to True to inherit the Pfquerytableviewcontroller class. The special variable self refers to the current scope, which is an instance of the class.
3. Then, we disable paging and set the maximum number of table objects to 25.
4. Finally, the parameter className is stored in the instance property Parseclassname.
After that, when we create an instance of the Catstableviewcontroller class, this construct (or specify initialization) will be the basis for the representation of the diagram controller being called and set.

Data retrieval with queryfortable encoding

The core of the Parse table view implemented through Pfquerytableviewcontroller is the method queryfortable. When we inherit the method, the inheritance is actually pfquerytableviewcontroller, so it needs to be rewritten: When a table view controller needs to be connected to the Parse data store, Pfquerytableviewcontroller calls it. It queries the data from the table, so the method is named Queryfortable. In this method, we can customize the search.
Add this method to the Catstableviewcontroller class (under the Viewdidload method). Note that these brackets match!

override func queryForTable() -> PFQuery {    var query:PFQuery = PFQuery(className:self.parseClassName!)    if(objects?.count == 0)    {        query.cachePolicy = PFCachePolicy.CacheThenNetwork    }    query.orderByAscending("name")    return query}

Take a look at this new method:

override func queryForTable() -> PFQuery

What does it contain? Write a new method, queryfortable, that tells the compiler the following:

1. Overwrite the parent method (the identity flag) with the same name and overwrite it with the statement.
Declare the method with Func and name, Queryfortable.
2. Declare the parameters between Methsignatureod. There are no parameters in this example.
3. Finally select "write→pfquery" and return to the method type.

The following changes have occurred within the method:

1. Declares a new variable to invoke the query, requires a named parameter of the class name, is used to instantiate the constructor's method, and the Self.parseclassname value is assigned. In other words, the table's class name is cat, which uses a cat instance to create a query.
2. Then, if the query is empty, set the CachePolicy property in the query. Its value is continuous pfcachepolicy.cachethennetwork, which means that the query first looks for an object in the offline cache, and if it is not found, it downloads the object from the online Parse data store. When the table view is finally displayed on the application interface, the IF statement executes successfully.
3. We then use the Name column as the query object.

Finally, the query results are returned. (not to be continued ...) )

Stay tuned: How to build an app like Instagram with the Parse and Swift series (2) (3).

Original address: Building an instagram-like App with Parse and Swift

This article is compiled and collated by OneAPM engineers. OneAPM is an emerging leader in application performance management, enabling enterprise users and developers to easily implement slow program code and real-time crawling of SQL statements. To read more technical articles, please visit the OneAPM official blog.

How do I build an app like Instagram with Parse and Swift?

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.