IOS development: Using AFNetworking in Swift

Source: Internet
Author: User

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.

 
  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'

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.

 
  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. Class var sharedInstance: RequestClient {
  4. Struct Static {
  5. Static var onceToken: dispatch_once_t = 0
  6. Static var instance: RequestClient? = Nil
  7. }
  8. Dispatch_once (& Static. onceToken, {()-> Void in
  9. // Enter the corresponding baseUrl for string.
  10. Var url: NSURL = NSURL (string :"")!
  11. Static. instance = RequestClient (baseURL: url)
  12. })
  13. // Return an instance of this class
  14. Return Static. instance!
  15. }
  16. }

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.

 
  1. Override func viewDidLoad (){
  2. Super. viewDidLoad ()
  3.  
  4. Self. view. backgroundColor = UIColor. brownColor ()
  5. Var image: UIImage
  6. // Customize the return button on the left of Navigationbar. Refer to the BaseViewController. swift file.
  7. Self. leftButton (nil, hlIimage: nil, title: "Returned", 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 succeeded + \ (responseObject )")
  23. }
  24.  
  25. Func failed (task: NSURLSessionDataTask !, Error: NSError !) -> Void {
  26. Println ("oh shit failed ")
  27. }

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.

 
  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. */

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.

Related Article

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.