IOS development: Using AFNetworking in Swift
Today, I will briefly explain how to use the popular AFNetworking request framework in the Swift project.
Currently, AFNetworking does not have the Swift version, so our project uses cocoapod to install AFNetworking.
This is my Prodfile file. cocoapod uses exactly the same method as OC. For convenience, we can create a class in the project and select the language OC, we will find that there will be an additional SwiftStudy-Bridging-Header.h file in the project, delete the created oc class, introduce here
Okay, you can use AFNetworking in the swift file.
- Platform: ios, '7. 0'
- Pod 'sdwebimage', '~> 3.7.1'
- Pod 'cocoahttpserver', '~> 2.3'
- Pod 'routinghttpserver', '~> 1.0.0'
- Pod 'masonry', '~> 0.6.1'
- Pod 'asihttprequest ',' ~> 1.8.2'
- Pod 'mbprogresshud ',' ~> 0.9.1'
- Pod 'afnetworking', '~> 2.5.4'
During project development using OC, AFNetworking is encapsulated externally. Today we will implement it using Swift.
All users who have used the new AFNetworking version know that it has a AFHTTPSessionManager. Here we inherit AFHTTPSessionManager and return an instance of this class in singleton mode,
In swift, The syntax for network operations is very different from that for OC. The Swift syntax is not described here. Please refer to The Swift Programming Language. Let's take a look at The code.
- //
- // RequestClient. swift
- // SwiftStudy
- //
- // Created by Yang Wende on 15/8/19.
- // Copyright (c) 2015 Yang Wende. All rights reserved.
- //
- Import UIKit
- Class RequestClient: AFHTTPSessionManager {
- Class var sharedInstance: RequestClient {
- Struct Static {
- Static var onceToken: dispatch_once_t = 0
- Static var instance: RequestClient? = Nil
- }
- Dispatch_once (& Static. onceToken, {()-> Void in
- // Enter the corresponding baseUrl for string.
- Var url: NSURL = NSURL (string :"")!
- Static. instance = RequestClient (baseURL: url)
- })
- // Return an instance of this class
- Return Static. instance!
- }
- }
After obtaining the RequestClient instance, we can encapsulate post, get, and upload image files.
In OC, AFNetworking is used to using blocks for data transmission. In Swift, we use closures for data transmission.
This is my file directory
SwiftStudy ------------ project directory
AppDelegate. swift
MyViewController. swift
ViewController. swift
NetWork ------------ NetWork problems
RequestClient. swift
RequestAPI. swift
Encapsulation of CustomVC ------------ VC,
CostomNavigationVC. swift
BaseViewController. swift
Here we mainly use the China weather Network API to test a PUT request. Let's take a look at RequestAPI. swift.
- Override func viewDidLoad (){
- Super. viewDidLoad ()
-
- Self. view. backgroundColor = UIColor. brownColor ()
- Var image: UIImage
- // Customize the return button on the left of Navigationbar. Refer to the BaseViewController. swift file.
- Self. leftButton (nil, hlIimage: nil, title: "Returned", size: CGSize (width: 38, height: 30), action: "buttonClick", target: self)
-
- Var dic: Dictionary = ["A": "a", "B": "B", "C": "c"];
-
-
- // Post test
- RequestAPI. POST ("List", body: dic, succeed: succeed, failed: failed)
- // Get test
- Var getUrl: String = "http://m.weather.com.cn/atad/101190101.html"
- RequestAPI. GET (getUrl, body: nil, succeed: succeed, failed: failed)
-
- // File Upload
- // Do any additional setup after loading the view.
- }
- Func succeed (task: NSURLSessionDataTask !, ResponseObject: AnyObject !) -> Void {
- Println ("oh my god succeeded + \ (responseObject )")
- }
-
- Func failed (task: NSURLSessionDataTask !, Error: NSError !) -> Void {
- Println ("oh shit failed ")
- }
In ViewController, we call the RequestAPI class method GET to obtain data. At the same time, we define two methods succeed and failed. Note that the parameters in the method and AFHTTPSessionManager
The parameters of the returned data are the same. In this way, the server returns all the data to us. Calling the GET method of equestAPI will pass a function pointer, after the network request is successful, the data is returned through the function pointer.
Then we can do other work.
If you have used the new AFNetworking version, you will often encounter 3084 1011 and 1016 errors. These errors are generally caused by data parsing errors. You can change the corresponding data type in AFNetworking, or you can define it based on your actual situation.
- /**
- RequestClient. sharedInstance. requestSerializer = AFJSONRequestSerializer ()
- RequestClient. sharedInstance. responseSerializer = AFJSONResponseSerializer ()
- RequestClient. sharedInstance. requestSerializer. setValue ("application/json, text/html", forHTTPHeaderField: "Accept ")
- RequestClient. sharedInstance. requestSerializer. setValue ("application/json; charset = UTF-8", forHTTPHeaderField: "Content-Type ")
- */
To sum up, AFNetworking is already the most widely used network framework. Further simple outer encapsulation of AFNetworking allows us to avoid a large amount of initialization work during network requests and directly use Singleton, this improves
Efficiency, saving a lot of code, at least looking at what you see is also quite comfortable, through the use of Swift to encapsulate AFNetworking, also the system is familiar with the basic syntax of swift, data type, and use of Singleton, closure, etc,
For beginners of swift, the actual learning effect is quite obvious. Now you can use swift to write a simple article or news. What are you waiting, as long as you rush forward, you will not end up.