(IOS) BAIDUFM Program Analysis

Source: Internet
Author: User

This article mainly shares the landlord in the study of swift programming process, on GitHub, an open-source app BAIDUFM research experience.

Project Address: Https://github.com/belm/BaiduFM-Swift

I. Introduction of the Project

Project through the use of Baidu Music API to achieve the play, download and collection of Music FM basic functions. At the same time, the lyrics scrolling, display real-time progress bar, support background playback, lock screen display song information and control playback and other additional functions and added support for Apple Watch. This app is very powerful, the following landlord to carefully analyze the code of this app and the principle of functional implementation.

Second, the APP iOS part analysis

Similar to the two apps previously analyzed by the landlord, this BAIDUFM is also based on the basic function of invoking the API to get song information and URLs from the network side. Here I will no longer specifically analyze the implementation of this function (unclear friends can see the landlord before the two blog post: (iOS) Swift Music program Analysis and (iOS) Swift2.0 Radio program analysis).

This time, this article mainly wants to explore how to design the program data structure through the analysis of the application program and data structures, so as to achieve the expected function with an efficient and concise code, and enhance the extension of the code to other functions. Also introduce some third-party libraries used by this app.

1. DataBase

One of the most significant differences between the two FM apps we analyzed earlier is that the author has designed a local datebase for this app. By invoking the third-party library Fmdb, the author establishes a SQLite database locally to hold the song information list. Then, first the landlord first to introduce the next fmdb this third-party library.

Fmdb is a third-party library that encapsulates the C language API with OBJECT-C for generating and managing SQLite on iOS devices. By calling the Fmdb library, users can easily use SQL commands to manipulate the database.

Github:https://github.com/ccgus/fmdb.

Specific instructions for use can be found in the blog post: http://www.cnblogs.com/wendingding/p/3871848.html.

In this project, the author establishes a fmdatabase locally through the creation of class Basedb and establishes a local music list database through class Songlist:basedb. Methods such as Func getAll ()->[song]?,func get (sid:string)->song are created by calling the Fmdcb method (see Code for details). Code are more understandable, the landlord does not do too much explanation, in this the only need to note that in the Fmdb use process, any other than select operations are considered to be updated. So the executeupdate (, Withargumentsinarray) method is used. Through the definition of the Songlist class, the author can easily add and delete modification data to the local database through the method of class.

2. Model

In addition to defining a database, defining the data model to be used in some apps is an integral part of the design process. In this link, the author defines 5 types of data altogether.

Three of these structs are: Songinfo,songlink and channel.

Songinfo: Contains the song ID, name, performer and other information.

Songlink: Contains the song link, the lyrics link, the format and so on information

Channel: Contains the channel ID, name, serial number and other information

Two x Class:class Song:nsobject and class DataCenter

Song: Is the data type that the database uses to record song information

DataCenter: Is an object similar to the Model Manager role that is used to provide a series of operations such as storing current radio information, current playlist information, playing song information, database operations, and so on. A single example of Sharedatecenter is provided to share itself.

3, Common

The author unifies some functions and constants that are often called into this folder.

Const.swift contains two notification names and the URL that the app needs, like this to unify the constant management, in the future to debug and modify and update it will be much more convenient.

Utils encapsulates a way to get a document path, which not only improves the efficiency of writing code, but also increases the readability of the code.

The common class contains a number of methods for song URLs, song images, display time, local song deletions, and lyrics processing. In this case, the author defines and uses a method of matching string regular expressions to split the time and lyrics portions of the LRC lyrics file and returns an array of lyrics time one by one.

For example: It is a LRC-formatted lyrics file. By passing this file into the function class Func PRASESONGLRC (lrc:string)->[(Lrc:string,time:int), the final returned array should be as follows:

Ret[0] = (LRC: "Glad You Came", time:0)

RET[1] = (LRC: "The Wanted", time:0)

RET[2] = (LRC: "", time:0)

RET[3] = (LRC: "The Sun Goes Down", time:1)

RET[4] = (LRC: "The Stars Come Out", Time:3)

...

Finally, in the common folder, the author calls Alamofire and Swiftyjson two third-party libraries in the HttpRequest class to define a series of methods for obtaining song information and downloading through a network request. Unlike the two apps previously analyzed by the landlord, the app does not use Swift's nsurlsession or nsurlconnect to make network requests, but instead calls third-party libraries Alamofire the APIs provided to achieve network communication. Let me start with a brief introduction to the third-party library of Alamofire.

Alamofire is a third-party library for HTTP network development. Its author is the author of the famous third-party library afnetworking. It can be said that Alamofire is the swift version of the afnetworking.

Github:https://github.com/alamofire/alamofire

The latest version of Alamofire is 3.0, which supports iOS 8+, Mac OS X 10.9+, WatchOS 2.0, Xcode 7 and Swift 2.0, and can be poured into project files through various tools such as Cocoapods,carthage.

This is a simple example of using the Alamofire.request method to get a response and use the. Responsejson to process the response result. For more examples of calling APIs, you crossing can go to GitHub to watch Alamofire's detailed tutorial guide.

With this simple example above, it is not difficult to find that the processing of URL requests and return results is so convenient compared to Nsurlsession,alamofire. That is, there is no need to complicate the definition of tedious session and task, while cooperating with the Swiftyjson library, can greatly reduce the processing of JSON format data used in the unpacking, transformation and other operations.

Then the landlord to introduce the same very useful third-party library Swiftyjson.

Swiftyjson is a third-party library for working with JSON-formatted data. Because of the swift language design, when you use the swift language to get the content of JSON-formatted data, you need to manually transform the Anyobject into a series of complex operations such as transformation and unpacking. At the same time in the process, a little careless, it is easy to cause the collapse of the program. Based on this, Swiftyjson provides a set of briefs on how to handle JSON-formatted data, without worrying about a program crash that occurs because of an array of exceptions caused by the neglect of processing on the JSON data.

Github:https://github.com/swiftyjson/swiftyjson

This is a simple example of invoking the JSON (data:) method. As you can see, you can get the data you want in just one step. This not only improves the efficiency of code writing, but also saves you from seeing a bunch of annoying unpacking steps as you read the code.

With the use of Alamofire JSON response handler, it greatly simplifies the process of processing the network when it returns JSON-formatted data.

4. View

The Views folder contains 7 files, 5 of which are tableviewcontroller contain a large number of table settings processing and filling, which is similar to the previous processing in two apps, this is not detailed to expand the narrative. The landlord will take out a few different places for a simple analysis.

All of the 5 Tableviewcontorller data sources are obtained by Datacenter.sharedatacenter Datacenter instances and then calling the corresponding methods. This approach avoids having to define variables in a class and pass data over and over again.

Animate the Willdisplaycell method by adding the Cell.layer.transform property setting and calling the Uiview.animatewithduration () method to achieve the cell display.

By calling the API in the third-party library Mjrefresh, the list has a pull-up refresh feature. The Mjrefresh is a third-party library used to implement a pull-up auto brush. You can easily implement the desired refresh function by invoking the API.

Github:https://github.com/codermjlee/mjrefresh

There are very detailed invocation examples on GitHub.

Views in addition to Tableviewcontroller defines a Roundimageview class that generates a circular uiimage for displaying song pictures. By setting the fillet of the picture, the fillet radius is set to 1/2 of the length of the square picture, so that the uiimage that are originally squares are displayed in a circle. and defines a rotation () method that rotates the picture.

Finally, viewcontrollere.swift in the main realization of song play, cut songs, download songs, favorite songs, update database, lock screen display and event response, display lyrics and other series of functions. Although the code is long and somewhat messy, the principle of functional implementation is relatively simple, not in detail here. The main point is to talk about the three third-party libraries used here: Async,ltmorphinglabel and Kingfisher.

Async is a third-party library that handles threading issues. Threading problems can be handled more conveniently by calling Async

Github:https://github.com/duemunk/async

With this example, you can see that the same code that performs a background operation and the main thread operation is much more concise after using the async library.

Ltmorphinglabel is a third-party library that implements the label display animation effect. When used, the Uilabel () instance is directly Ltmorphinglabel (), and then the various animation effects provided in the Ltmorphinglabel class can be called.

Github:https://github.com/lexrus/ltmorphinglabel

Kingfisher is a third-party library that uses an asynchronous download to load and cache pictures. All of the downloads are asynchronous and do not have a card UI, and while the download is complete, it not only provides the memory cache, but also provides a backup of the local disk.

Github:https://github.com/onevcat/kingfisher

Iii. talk about third-party libraries

During the analysis of the program section, we talked about all the third-party libraries used in the app and gave a brief introduction. Let's do a summary here.

Fmdb:https://github.com/ccgus/fmdb

Alamofire:https://github.com/alamofire/alamofire

Swiftyjson:https://github.com/swiftyjson/swiftyjson

Mjrefresh:https://github.com/codermjlee/mjrefresh

Async:https://github.com/duemunk/async

Ltmorphinglabel:https://github.com/lexrus/ltmorphinglabel

Kingfisher:https://github.com/onevcat/kingfisher

Now you want to talk about how to introduce these libraries into your project.

Today, in the Swift project, the third-party library is referenced and managed by both the Cocoapods and Carthage tools. Then let's briefly talk about the two tools and how to use them.

1, CocoaPods

Cocoapods can be said to be the most popular Iso/mac third-party Library management tool at present. The latest version is 0.39. By writing podfile and executing it, users can easily get the third-party libraries they want to use from GitHub and integrate them into their projects.

Official website: https://cocoapods.org

Install Cocoapods:

Enter the code in the terminal to complete the Cocoapods installation automatically.

After the installation is the introduction of how to use this very useful tool

The first is to create a podfile file under the project directory. Writes a third-party library, such as format, required by the project to Podfile.

Then use the terminal to enter the project directory to run the command pod install, wait a moment, the screen will prompt installation success.

You can then open the project with the newly generated. xcworkspace file.

Advantages of Cocoapods:

Extremely convenient to use, in addition to writing Podfile, the rest of the operation is done automatically.

Support for a large number of third-party libraries.

2, Carthage

The biggest advantage compared to cocoapods,carthage is to be centralized. When you call a third-party library with Carthage, you do not create an additional. Xcworkspace, which means that users have free control over how to load third-party libraries into their own projects.

Github:https://github.com/carthage/carthage

Install Carthage:

Download the carthage.pkg and install it in the https://github.com/Carthage/Carthage/releases.

How to use Carthage can refer to http://devtian.me/2015/08/11/translate-carthage-readme/this blog post is a translation of the Carthage instructions.

Iv. The iOS part of the project can be improved partly

The project is highly efficient and well-laid in the data model design, but there is a huge class that integrates many functions and methods such as Viewcontroller.swift. This not only increases the reading difficulty of the code, but also increases the difficulty of the program in the process of updating and maintaining.

V. Summary

The production of this project is more sophisticated, the author through the use of a large number of third-party libraries such as Fmdb,alamofire,swiftyjson not only reduce the project to achieve the difficulty of the function, but also the readability of the code has been a certain increase. Through the introduction of these third-party libraries, the landlord believes that in the future in the actual process, reasonable use of third-party library will be to improve the code and project quality is a good way and means.

The Apple Watch section is also included in this project, and the landlord will conduct a detailed analysis of the section later.

(IOS) BAIDUFM Program Analysis

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.