"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 is the 3rd article in this series, compiled and collated by OneAPM engineers.
How do I build an app like Instagram with Parse and Swift? (1)
How do I build an app like Instagram with Parse and Swift? (2)
Using Swift and custom table view cells
Now let's return to the code again-there are enough interfaces. Open Catstableviewcontroller.swift and locate the specified initialization init (style: Class name:).
In this method, we can add the following two lines of code under Self.parseclassname = ClassName:
self.tableView.rowHeight = 350
self.tableView.allowsSelection = false
The first line sets the appropriate row height, and the second row disables cell selection.
Then add the following code to viewdidload just above super.viewdidload (): Method
tableView.registerNib(UINib(nibName: "CatsTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)
The row is likely to throw an error. To try to be as error-prone as possible, move the following code from the TableView Cellforrowatindexpat method to the top of the class and re-name its value "catcell".
let cellIdentifier:String = "Cell"
The definition of a class should look like this:
class CatsTableViewController: PFQueryTableViewController
{
let cellIdentifier:String = "CatCell"
override init!(style: UITableViewStyle, className: String!)
}
We have just extended the Cellidentifier constant from the local method scope into a class scope, making it available throughout the class, including the TableView Cellforrowatindexpath and Viewdidload.
Next, we replace the contents of TableView's Cellforrowatindexpath with the following code:
var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil)[0] as? CatsTableViewCell
}
if let pfObject = object {
cell?.catNameLabel?.text = pfObject["name"] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil {
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
}
return cell
You can't help wondering, how does this differ from the old code we used before? Mainly reflected in:
- Cell type changed from Pftableviewcell to Catstableviewcell
- When the cell is empty, the new cell is obtained from the XIB file that we just created. We will retrieve from the collection, give all the current class ownership, and then convert it to Catstableviewcell.
- We then check to see if the object exists and attempt to assign the column name of the Parse object to its Text property, as before.
- The Catvoteslabel and Text properties are then the same. Parse Each column is a String type, but not an int, so would you like to convert it to int type? If the number of votes is exactly null, then we'll set it to zero. Then, use a technique called string interpolation to set the label text.
Finally, we return to the cell.
Let's run the application again. Everything looks So perfect! No bugs and crashes! But... Where's the image?
Download images asynchronously from Parse
The image is gone, how can it be! Let's add it. Add the following code to the TableView Cellforrowatindexpath "after the last if statement (for the credit label), before the return statement."
var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil)[0] as? CatsTableViewCell
}
if let pfObject = object {
cell?.catNameLabel?.text = pfObject["name"] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil {
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
}
return cell
Wow! What's going on here? We turn the Parse URL column into an instance of the Nsurl type.
We use it to start an asynchronous nsurlconnection in the main operations queue, where the image is downloaded as a NSData object. Close execution when the download is complete. It assigns the downloaded data to the UIImage and assigns it to the Catimageview image attribute.
There is no need to delve too deeply here, because the complexity of the code above is irrelevant to our application. However, please note the following points:
- It's easy to use nsurlconnection, but it's boring. When you use data sources on the Internet to do more complex things, choose the excellent afnetworking (objective-c) or Alamofire (Swift) library.
- Parse allows you to store images in the cloud and to use them directly. It is part of the Parseui, but it does not allow the invocation of external URLs (CAT images originating from Flickr).
- Before we start another asynchronous connection, we first need to identify all the operations in the primary queue. This is a bit boring: it removes pending-and-unfinished downloads from the queue. Try to delete the line and run the program, and you will see all the images mixed into a heap. When it re-uses the cell, the dequeue mechanism does not reset any pending connections, so the image can be loaded successfully.
Let's run the app again to see if it works.
Overweight: Similar features on Instagram
It's not easy to take this step! Some of the ultimate features remain to be perfected. Next, let's add these features: similar to the "instagram" feature-you double-click on the picture, a "like +1" is added to the cat's picture, and show a clean kitten claw animation. "
First, add an exit for the paw image to the table view cell. Add the following line of code to the Catstableviewcell class (below the other four exits):
@IBOutlet weak var catPawIcon:UIImageView?
Add a Uiimageview to Catstableviewcell.xib in Interface Builder. Do you remember how to do it?
- Find the Uiimageview class in the object library.
- Drag and drop it from the object library into the table view cell.
Make sure to drag it to the right to the center of the other image view. Adjust the new image with a width height of 100 points, and its X and Y are about 110 points. Then, when the image view is selected, the following restrictions are added.
- Editor→pin→width
- Editor→pin→height
- Editor→pin→top Space to Superview
- Editor→align→horizontal Center in Container
As shown, the image view is centered horizontally, with a fixed width and height of 100 points, and keeps it with a fixed space on the top, effectively centering the cat image in its center.
Now create an egress connection by selecting the Cat's Table view cell from the top of the document. Then select the Connections Inspector tab and draw a blue line from the Catpawicon cell image view.
Next, download Paw.zip. The file contains three graphics files, which are three resolutions of an image. You need to import them before you use them.
First, unzip the file, then open the Images.xcassets file in Xcode, then right-click the list on the left (a list that says APPICON), and then click New Image Set, or use the "Plus" button at the bottom left. Rename the image set you just created, and open its properties.
Now, drag the file you just unzipped from the Finder to the open file set. Make sure the file matches:
- Paw.png is 1x.
- [Email protected] is 2x.
- [Email protected] is 3x.
Don't worry if you can't see the files, because they're all white.
Then, return to Catstableviewcell.xib and select small Image view. Locate the property inspector, and then select the appropriate paw image from the image drop-down list. The white paws should appear like this in the cell view.
Finally, remember to connect with Catpawicon exit and small image view.
Now, let's go back to coding. Open the Catstableviewcell in Xcode. Add the following code to the Awakefromnib method (before super.awakefromnib ()).
let gesture = UITapGestureRecognizer(target: self, action:Selector("onDoubleTap:"))
gesture.numberOfTapsRequired = 2
contentView.addGestureRecognizer(gesture)
catPawIcon?.hidden = true
There are two things that happen here.
-
First, we create a uitapgesturerecognizer so that we can interact with any view. In this case, we add it to the Contentview view, which includes the cell's two labels and two image views. It is Ondoubletap: Initializes a target, self, an action, and a selector. Therefore, when a continuous double-click is detected, the method Ondoubletap:of self (the current class) is executed. In addition, we set the number of consecutive numbers to 2, making it a double-click Response.
-
Second, we hide the Catpawicon exit.
Next, add the Ondoubletap method to the current class (after the awakefromnib (): function).
func onDoubleTap(sender:AnyObject) {
catPawIcon?.hidden = false
catPawIcon?.alpha = 1.0
UIView.animateWithDuration(1.0, delay: 1.0, options:nil, animations: {
self.catPawIcon?.alpha = 0
}, completion: {
(value:Bool) in
self.catPawIcon?.hidden = true
})
}
This method is called an action and always requires a parameter: Anyobject. In this method, you can implement the following animation code:
- First, make Catpawicon visible by setting hide to false.
- Then, set Alpha as transparency to 1.0, which is fully visible. The image state needs to be reset, that is, when the animation is complete, the alpha channel is 0.
- The settings for the animation need to be programmed. The UIView class method is used, which requires five parameters: Animation time, pre-animation delay, basic options, the closing of animation properties, and the instruction to close when the animation is complete.
At this point you will see:
- To make the image visible, we can set its alpha channel to be visible.
- Wait a minute. Animation delay.
- The animation alpha channel takes less than a second from 1 to 0, which is the animation cycle.
- The animation is complete, hiding the image.
The biggest benefit of this solution is its ease of use: The code will fully manage the animation. We only need to set its initial state, end state, duration, and animation frame interpolation status and animation steps. Technically, we use two attributes: A sequential value α, a Boolean value that hides the visibility of the image that manages the paw.
Finally, run the app to see if the new feature works. You can double-click a cell, briefly show the Paw icon, double-click and fade Away.
Can you run it? That's great!
Integrate voting with Parse
The only thing left to do is to add a voting sequence to the Parse cat object and double-click to respond to the voting action.
So how do we make it?
First, the object we want to change is called the object of the Pfobject type, in the Cellforrowatindexpath method of the Catstableviewcontroller TableView. We cannot access it from the Table view unit because it is within the method of double-clicking the action.
We can't move the Ondoubletap method, so we need to create a reference between the table View object and the table view cell.
We take the following steps to achieve:
1. In Catstableviewcell, at the top of the class and at the dot, write the following code to create a new property:
var parseObject:PFObject?
2. Then, in the Cellforrowatindexpath of TableView, write the following code (just after the curly brace for the end of the cell = = Nill statement), as follows:
cell?.parseObject = object
Now we have a mechanism to copy the Cellforrowatindexpath object to our table view unit, making the object instance available in the Catstableviewcell class.
Then, adjust the Ondoubletap method of the Catstableviewcell. Add the following code at the beginning of the method:
if(parseObject != nil) {
if var votes:Int? = parseObject!.objectForKey("votes") as? Int {
votes!++
parseObject!.setObject(votes!, forKey: "votes");
parseObject!.saveInBackground();
catVotesLabel?.text = "\(votes!) votes";
}
}
This code can do the following:
- Check if the parseobject is empty;
- Get the number of votes from parseobject and place it in an optional Int;
- If the number of votes is not empty, use the + + operation to increase the number of votes variable, with votes = votes! + 1 has the same function;
- Use the SetObject function to return the ticket number variable to the parseobject set;
- Call Parseobject's Saveinbackground () Method! It will save the current object in the background and, if possible, write it to the Parse cloud;
- Update the text to feed back the new number of votes, everything is so simple,Playrun the program with Command-r or buttons to verify that the new feature is implemented.
Did it run successfully? It's great!
Summary:
Through this article, we learned the following:
- 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.
You can download the entire Paw project file here. Run the project using the Xcode6.3 (or above) version. Note that you must change the application key and client key in Appdelegate.swift. Also keep in mind that if you write the complete App yourself, it's a great opportunity to improve yourself. End
How do I build an app like Instagram with Parse and Swift? (1)
How do I build an app like Instagram with Parse and Swift? (2)
Original address: http://www.appcoda.com/instagram-app-parse-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? (3)