This tutorial has been updated for Swift, iOS 8.3, Xcode 6.3, and the latest Parse SDK (version 1.7.1). Network backend support can add many new features to your App: data synchronization, social sharing, and cloud storage can all be handled with ease. As a professional iOS developer, how can you add server-side support to your App? In this Parse tutorial, you will learn how to create an App that uses Parse backend support. The main function of this App is photo sharing, including user login, photo upload and photo wall functions. In order to allow you to focus on the implementation of aParse, this project pre-includes part of the user interface, but does not include the functions of uploading and displaying photos. You will add Parse services step by step to complete a complete App. Are you ready to create apps with ease? Okay, let’s get started with Parse. Preparation Before starting the App development work, the first step is to create a Parse App in the background. Every developer and every App needs a unique identifier, otherwise your data and users will be mixed up with others. Visit Parse.com, click “Get started for free”, then click Sign up to create a new account. After creating your account, Parse will ask you if you want to create your first app. You must register a separate backend app for each iOS app. In this tutorial, we call it "Tutorial App". There may be many apps on Parse, each with a different identifier, but right now there is only one app instance that belongs to you. After creating the app, you will see a welcome screen with many options to help you add Parse functionality. These options will have templates available for download, but they are not needed for this tutorial. There are several option buttons at the top of the page, as shown below: Here is a description of the options:
Parse Example Program To focus on the backend service, this tutorial includes a starter project that you can download directly and then follow the tutorial steps to add Parse calls. Open the project in Xcode and run it. First, you will see a login page. But the buttons on this page don't do anything yet. You will learn how to create these functions later. Before we get started, open the Main.storyboard file to take a look at the structure and flow of the app. The project contains the following 4 main views:
Each view has a corresponding UIViewController in the Storyboard, but you’ll notice that the “Photo Wall” view has two representations. This is because you’ll see two ways to implement this view using Parse. Parse Fast Prepare The first step, of course, is to configure your project to use Parse. Download the Parse iOS SDK using the following link: https://parse.com/downloads/ios/parse-library/latest After downloading, unzip and drag the three framework files in the frameworks folder into your project. When the prompt box appears, select "Copy items..." and "Create groups...". Xcode will add these frameworks to the "ParseTutorial" target by default, no additional configuration is required.
Note: When adding Parse to an existing project, you will also need to add some of the Parse framework’s dependencies, such as CoreGraphics and SystemConfiguration. Our starter project already includes these, and you can find the complete steps in the "Parse Quick Start Guide". The Parse SDK is implemented in Objective-C, and you will use Swift to create your app. To use the Parse Obj-C SDK in a Swift program, you need an Objective-C bridging header file. The easiest way to create a bridging header file is to add any Objective-C file to your project. Xcode will automatically create the header file for you. In Xcode, select File\New\File... and choose the iOS\Source\Objective-C file template. Name it whatever you want (we will delete the file later), then save it. When you save this file, Xcode will provide an Objective-C bridging header file. As shown in the figure: After clicking Yes, Xcode will create a bridging header file and add it to your project. The Objective-C file is no longer needed and can be deleted directly. Open the newly created "ParseTutorial-Bridging-Header.h" file and add the following content to the bottom of the file:
Next, you need to get the API key for our app from the Parse website. Open your app's Settings interface on the Parse Dashboard and select the Keys button on the left panel. Make a note of the Application ID and Client Key. Next, open the AppDelegate.swift file and locate application(_:didFinishLaunchingWithOptions:). Add the following to the beginning of the method:
Of course, you need to fill in the real ID and Key you wrote down earlier in the AppID and clientKey positions. Build and run the app. If there are no errors, it means the app has been registered and connected to the Parse backend. You can now call Parse related services. In the next step, we'll create some sample objects. #p# Creating a Sample Object Each Parse object uploaded becomes an entry point to the database structure. You can think of these objects as dictionaries - data is stored in advance with keywords, and then you can get the object by keyword. In this example, you will upload an object called "Player" with two fields "Name" and "Score". Therefore, in the database, there will be a table called "Player" containing all objects uploaded with the name "Player". You will see an example of this later. Open AppDelegate.swift and add the following code to application(_:didFinishLaunchingWithOptions:) before the return true statement.
As you can see, the code that uploads the object is asynchronous and you will check the result in the closure. PFObject is a base class in Parse, which provides some basic object operation methods. The biggest benefit is that you don't need to create a table on the Parse website, Parse will create the table structure based on the object you submit. Build and run. If you placed the API key correctly and the app registered with the Parse service correctly, the app should run fine. Otherwise, you will receive an error message. Wait, where did your partner go? Just floating around in cyberspace? To view the objects you saved correctly, just open the Parse dashboard and click Core. You should see the objects as shown below: Congratulations, you have successfully interacted with the network backend. Note: If you run the app on the iOS Simulator and see an error message such as "The network connection was lost", try restarting the simulator. This method can also be used to try other network errors. If you have received the "Object Uploaded" message but do not see data on the Dashboard, please click the "Refresh" button in the upper right corner to refresh the Dashboard page. Before moving on to the next step, create another data item. Set the name to "John" and the score to 810. Now you have two data items, both with the name John, but different scores. Add a third data item with the name "Sally" and the score to 2400. Get Object Now, let’s try to fetch an object. Parse has the PFQuery class to support this. It can perform data queries, and you can read more about it in the PFQuery documentation. Let's implement getting objects that meet the following conditions: score is greater than 1000, and name is equal to "John". Comment out (or delete) the previous code, otherwise a new object will be uploaded each time it is run. Then place the following code:
Build and run the app again. The data request is asynchronous, so it won’t slow down the UI display—which makes your users happier. In the console, you should see all the objects that meet the criteria, as shown below: Now that we have explored the basic operations for storing and retrieving data, let's apply them in a real project. Remember to comment out the code we just wrote in application(_:didFinishLaunchingWithOptions:) first. User Registration First, users will register an account using our app. Open RegisterViewController.swift. Currently, this interface can’t do anything. Our task is to implement the function after clicking the “Sign Up” button. Locate the signUpPressed(_:) method and replace the code with the following:
In the above code, create a user according to the following steps:
Build and run the app to see if there are any errors. In the Log In interface, click the Sign Up button and you will see the following interface:
Enter your username and password, click the Sign Up button, and if everything goes well you will be redirected to the photo wall interface. That’s good, but to be on the safe side, let’s verify whether the new user has actually been created successfully in the table: Open the User option in the Dashboard, as shown below: Congratulations! You have created your first user. Now let's log in with this user and do some interesting things. Log in Open the LoginViewController.swift class and find the following method:
As you can see, this method is very similar to the one in the registration process. We are still using PFUser here, but for login. Replace the code in the method:
The process is very simple. Before jumping to the next screen, we first check whether the username and password match the records in the database. Build and run the program, the effect is as follows: Try to log in with the user we created. If everything is normal, the app will jump to the photo wall interface. To be on the safe side, you can try to log in with an incorrect username or password to see if there is an error code displayed. #p# Post photos to the photo wall The previous registration and login operations will jump to the photo wall view. In this view, you will see all the pictures and comments uploaded by users. Before that, we have to upload some pictures. Uploading files with Parse is simple. Open UploadImageViewController.swift, where we will implement the upload functionality. All users who log in can click the "Upload" button to jump to the upload view.
Here, users can choose to enter notes and click "Select Picture" to use the system's standard image picker to get a photo from the photo library and upload it. All of the above code has been implemented in the starter project. Now we need to implement the sendPressed(_:) code. This action method is connected to the "Send" button in the navigation bar. It sends the photo and note to the server. We have seen before that we can use the setKey and objectForKey methods to add and get fields of PFObject. But now we need to use a specific object type (photo wall), at this time, a custom subclass can play a better role. Next you will see how to do it. Customizing the Parse Object Open the WallPost.swift file in the Model group. You will now see a simple class that inherits from the NSObject class. First, change the parent class so that it inherits from PFObject:
You also need the WallPost class to conform to the PFSubclassing protocol. The PFSubclassing protocol defines some necessary methods for inheriting PFObject. The categories defined in PFObject+Subclass.h implement these methods, and what you need to do is to override them in your own subclass. The specific method is to add an extension to the WallPost class, which contains these two necessary methods:
Next, we add three properties to the WallPost class:
Here, we use the PFFile type image to store the uploaded photos, the PFUser type user to store user information, and the String type comment to store photo comments. We use @NSManager because from a low-level perspective, the properties of PFObject are just a collection of key-value pairs. When we set a property, it is automatically set as a key-value pair. In addition, we need to define a query() method in the subclass to return a PFQuery object. Add the following code to the WallPost.swift file:
Here is a detailed description of this code:
***, we need to add an initialization method.
The above is a simple initialization method. Regardless of whether an initial value is given, a WallPost object can be created. Now that WallPost is complete, let's move on to uploading photos. Open UploadImageViewController.swift and add the following code to the end of sendPresed(_:) :
Here are the detailed instructions:
Next, implement the saveWallPost(_:) method:
The detailed instructions are as follows:
Build and run the app. Log in as the user you created earlier, enter the picture upload interface, click the "Select Picture" button, select a picture from the photo library, write a note, and click the "Send" button. In the console you can see the percentage of the upload. Here we just display it in the console. In the final version of the app, it would be more appropriate to display a progress bar with this progress. On the Dashboard, view the Core data and you will see a new table called WallPost. Not bad, but the only downside is that you can’t see the uploaded photos in the app. Then our next step is to realize the function of retrieving photos. #p# Showcase photos on your photo wall Open WallPicturesViewController.swift, this view will display all the photos uploaded by the user. When the view loads, it calls the getWallImages() method to get all the objects, which are currently empty. For this to work, we first need to add some code to fetch the photos and place them on the wall. Add the loadWallViews(_:) method:
First we clear all UIView objects on the scrollview. Then we use the fast enumeration method to traverse the objects in the array, and for each object, perform the following steps:
Now, replace the contents of the getWallImages() method:
Detailed description:
Build and run the app. You will see the pictures and notes you uploaded earlier. Take some time to play around with it and add more pictures and notes. Then check out the photo wall. Pretty cool, isn't it? Parse UI As mentioned before, there is another way to display saved images. Let's take a look at this method next. In the previous example, we used a simple UIScrollView object to display pictures, which requires us to calculate the content size ourselves. You may have thought that it might be better to use UITableView. Of course, smart Parse developers have already considered this, so they wrote ParseUI.framework, which provides a lot of convenient things to display Parse-related UI. We mainly look at the following three:
Now, open WallPicturesTableViewController.swift and change its superclass from UITableViewController to PFQueryTableViewController. Of course, WallPostTableViewCell must also inherit from PFTableViewCell, and the type of the postImage object must also be changed to PFImageView. Before writing any code, we need to make some changes to the storyboard. Open Main.storyboard and find the WallTableView scene: Open the Attributes Inspector and you’ll see an option that includes a PFQueryTableViewController parameter: These parameters allow you to choose the type of object to display in the table. You can also specify pull-to-refresh, paging, and loading interfaces. When using a simple UITableview to display the results, you can even set the key of the PFObject field to be displayed in the table without having to set it in code. In the Parse Class parameter, fill in WallPost. Now go back to WallPicturesTableViewController.swift and add the following method:
Each time the photo wall interface is displayed, we want it to be reloaded. To specify the request to run, we override the queryForTable() method to return a query object for WallPost. ***, add the following tableview delegate method:
This method replaces the native data source method of UITableView, tableView(_:cellForRowAtIndexPath:), which is more appropriate because it directly passes the PFObject object without looking up the corresponding object through the index path. Let's take a look at the specific code explanation:
There’s one last step before running the code. Open LoginViewController.swift and replace the scrollViewWallSegue with a tableViewWallSegue in loginPressed(_:) . Do the same in RegisterViewController.swift so that you can jump to the new version of the photo wall view. Build and run the app. You’ll see the photo wall displayed in the table view, and a progress bar updating as the photos are downloaded. #p# Stay logged in, log out You should have realized that every time the app is launched, the user needs to log in again. In addition, the "Log Out" button only takes the user to the main interface every time without actually logging out. In the last part of the tutorial, we will add the ability to remember the logged-in state even if the app is restarted. We will also add a true logout feature. Open LoginViewController.swift and add the following code to viewDidLoad():
Once the user is logged in, Parse will remember the user and state when the app is restarted. Here we use optional binding (if let) to check if the user currently exists. If so, we check if the user is authenticated. If so, the user is logged in and we jump directly to the photo wall view. To log the user out, open WallPicturesTableViewController.swift, find logOutPressed(_:) and add the following code:
Here we simply log out the current user and jump to the initial login interface. Remember to add the same logout code in WallPicturesViewController.swift. Build, run, and you’re done! What's next? This link contains the complete example project: http://cdn4.raywenderlich.com/wp-content/uploads/2015/04/ParseTutorial-Finished.zip You have seen how it is convenient to use PFObject subclasses to upload and download objects. You have also learned how to use PFUser in Parse. You can accomplish more with Parse. Parse also supports sending push notifications to your users within the app. There are more social features integrated into the framework. You can also add data analysis to record user behavior. Parse provides more advanced features, such as writing cloud code and scheduling recurring tasks in the background. As you write your Parse apps, you’ll get to know it better, and I highly recommend you explore more advanced features. Now, you should be confident about adding backend functions. Creating a cloud application is no longer an unattainable task. I hope to see you build more apps based on Parse. If you have any questions or suggestions, please join the forum to discuss. |
<<: Microsoft releases ASP.NET 5 version roadmap
The day before yesterday, I shared an article: &q...
With regard to information flow advertising, ther...
Course Contents: 01.Understand the value of Xiaoh...
Li Jiaqi, a man that women love and hate. It is s...
Some time ago, WeChat was updated on both Android...
[[120974]] CocoaChina: How did you get involved i...
Holiday marketing planning has obvious advantages...
This article is compiled from Zhihu: Zhihu user: ...
In the era of mobile Internet, traffic costs are ...
In this era where mobile phone addiction is rampa...
Weibo's market value today has reached 10 bil...
[[173106]] In this evaluation, AnandTech still us...
In fact, the meaning behind the data is logic and...
This article mainly introduces how to improve the ...
The rules of the Otaku Points-Based Management Ga...