How to use AFNetworking in Swift

How to use AFNetworking in Swift

[[147119]]

Apple released the new Swift language at WWDC in 2014, and 2.0 was officially released not long ago. As an iOS developer, you must keep up with the pace. Therefore, in my spare time recently, I started to rewrite my own projects in Swift and learn new syntax and design patterns. Since I have a relatively short time to learn Swift, today I will briefly talk about how to use the popular AFNetworking request framework in Swift projects.

Since there is currently no Swift version of AFNetworking, our project uses cocoapod to install AFNetworking.

This is my Prodfile file. The method of using cocoapod is exactly the same as that of using OC. For convenience, we create a class in the project and select the language OC. We will find that there will be an extra SwiftStudy-Bridging-Header.h file in the project. Delete the created OC class and introduce it here.

OK, you can use AFNetworking in Swift files

  1. platform :ios, '7.0'  
  2. pod 'SDWebImage' , '~> 3.7.1'  
  3. pod 'CocoaHTTPServer' , '~> 2.3'  
  4. pod 'RoutingHTTPServer' , '~> 1.0.0'  
  5. pod 'Masonry' , '~> 0.6.1'  
  6. pod 'ASIHTTPRequest' , '~> 1.8.2'  
  7. pod 'MBProgressHUD' , '~> 0.9.1'  
  8. pod 'AFNetworking' , '~> 2.5.4'  

When using OC for project development, a simple external encapsulation of AFNetworking was made. Today we will implement it in Swift.

Anyone who has used the new version of AFNetworking knows that it has an AFHTTPSessionManager. Here we inherit AFHTTPSessionManager and use the singleton mode to return an instance of this class.

The way to write a singleton in Swift to perform network operations is very different from the OC syntax. I won’t explain Swift syntax here. Please refer to "The Swift Programming Language". Let’s take a look at the code

  1. //  
  2. // RequestClient.swift  
  3. //SwiftStudy  
  4. //  
  5. // Created by Yang Wende on 15/8/19.  
  6. // Copyright (c) 2015 Yang Wende. All rights reserved.  
  7. //  
  1. import UIKit
  2. class RequestClient: AFHTTPSessionManager {
  3.      
  4. class var sharedInstance :RequestClient {
  5. struct Static {
  6. static var onceToken:dispatch_once_t = 0  
  7. static var instance:RequestClient? = nil
  8. }
  9.          
  10. dispatch_once(&Static.onceToken, { () -> Void in
  11. // string fill in the corresponding baseUrl  
  12. var url:NSURL = NSURL(string: "" )!
  13. Static.instance = RequestClient(baseURL: url)
  14. })
  15. //Return an instance of this class  
  16. return Static.instance!
  17.          
  18. }
  19. }

With the instance of RequestClient, we can encapsulate post, get and upload image files.

When using AFNetworking in OC, we are used to using blocks to transfer data, etc. In Swift, we use closures to transfer data

This is my file directory

SwiftStudy ------------Project Directory

AppDelegate.swift

myViewController.swift

ViewController.swift

NetWork ------------Network related

RequestClient.swift

RequestAPI.swift

CustomVC ------------VC encapsulation,

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.

  1. override func viewDidLoad() {
  2. super .viewDidLoad()
  3.  
  4. self.view.backgroundColor = UIColor.brownColor()
  5. var image:UIImage
  6. //Customize the back button on the left side of the Navigationbar, refer to the file BaseViewController.swift  
  7. self.leftButton(nil, hlIimage: nil, title: "Return" , size: CGSize(width: 38 , height: 30 ), action: "buttonClick" , target: self)
  8.  
  9. var dic:Dictionary= [ "A" : "a" , "B" : "b" , "C" : "c" ];
  10.  
  11.  
  12. //post test  
  13. RequestAPI.POST( "List" , body: dic, succeed: succeed, failed:failed)
  14. //get test  
  15. var getUrl:String = "http://m.weather.com.cn/atad/101190101.html"  
  16. RequestAPI.GET(getUrl, body: nil, succeed: succeed, failed: failed)
  17.  
  18. //File upload  
  19. // Do any additional setup after loading the view.  
  20. }
  21. func succeed(task:NSURLSessionDataTask!,responseObject:AnyObject!)->Void{
  22. println( "oh my god it worked + \(responseObject)" )
  23. }
  24.  
  25. func failed(task:NSURLSessionDataTask!,error:NSError!)->Void{
  26. println( "oh shit failed" )
  27. }

In ViewController, we get data by calling the GET method of RequestAPI. At the same time, we define two methods, succeed and failed. Pay attention to the parameters in the method and AFHTTPSessionManager.

The parameters of the returned data are the same, so the data we get is all the data returned by the server. Calling the GET method of the requestAPI will pass a function pointer, and the data will be returned through the function pointer after the network request is successful.

Then we can proceed to other work.

If you have used the new version of AFNetworking, you will often encounter errors 3084, 1011, and 1016. These errors are generally data parsing errors. You can change the corresponding data types in AFNetworking, or you can define them yourself according to actual conditions.

  1. /**
  2. RequestClient.sharedInstance.requestSerializer = AFJSONRequestSerializer()
  3. RequestClient.sharedInstance.responseSerializer = AFJSONResponseSerializer()
  4. RequestClient.sharedInstance.requestSerializer.setValue("application/json,text/html", forHTTPHeaderField: "Accept")
  5. RequestClient.sharedInstance.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
  6. */  

In summary, AFNetworking is already the most used network framework. By further encapsulating AFNetworking in a simple outer layer, we can avoid a lot of initialization work when making network requests and directly use a singleton, which improves

Efficiency, but also save a lot of code, at least at a glance, it is more comfortable to read. By using Swift to encapsulate AFNetworking, you can also systematically become familiar with the basic syntax, data types, and the use of singletons, closures, etc. of Swift.

For Swift beginners, the actual learning effect is quite obvious. With these, you can now use Swift to write a simple joke or news. What are you waiting for? As long as you move forward, you will not fall behind.

<<:  Survey shows that most developers have never built a mobile app

>>:  Don’t look down on the three lows, they are the battleground on social networks!

Recommend

How long can a cut watermelon be kept, 1 day, 2 days?

Let me give you the answer first: It is recommend...

How to promote WeChat mini program to attract new users?

In the era of mobile Internet, traffic costs are ...

Status bar prompts with various effects

Source code introduction The demo can provide a v...

Fun fact: How did toast come about and why has it existed for so long?

In 2015, China's Tusi sites were included in ...

Introduction to creative types of 360 search advertising promotion!

What is creativity? Creativity refers to the prom...