China Naming Network - Company naming - How to use AFNetworking in Swift

How to use AFNetworking in Swift

As there is no Swift version of AFNetworking at present, our project uses cocoapod to install AFNetworking.

This is my Prodfile file, and the usage of cocoapod is exactly the same as when using oc. For convenience, we will randomly create a class in the project, select the language OC, and we will find that there will be an additional SwiftStudy-Bridging-Header.h file in the project, and delete the created OC class, which is introduced here.

Ok, you can use AFNetworking in swift files.

Platform: ios, "7.0"

pod 'SDWebImage ',' ~ & gt3.7. 1'

pod 'CocoaHTTPServer ',' ~ & gt2.3'

pod 'RoutingHTTPServer ',' ~ & gt 1.0.0'

Pod' masonry',' ~ & gt0.6. 1'

pod 'ASIHTTPRequest ',' ~ & gt 1.8.2'

pod 'MBProgressHUD ',' ~ & gt0.9. 1'

pod 'AFNetworking ',' ~ & gt2.5.4'

When using OC for project development, we made a simple external package for AFNetworking, and today we will implement it with Swift.

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

For network operation, the writing of singletons in swift is very different from OC grammar. Swift syntax is not explained here. Please refer to the Swift programming language, and let's look at the code.

Import UIKit

Class requestclient: afhttpsessionmanager {

Class var shared instance: requestclient {

Static structure {

Static variable onceToken:dispatch_once_t = 0.

Static var instance: RequestClient? = zero

}

dispatch _ once(amp; Static.onceToken,{()-& gt; invalidate

//string only needs to fill in the corresponding baseUrl.

var url:NSURL = NSURL(string:" ")!

static . instance = request client(base URL:URL)

})

//Returns an instance of this class.

Return Static.instance!

}

}

Using an instance of RequestClient, we can package post, get and upload image files.

AFNetworking is used to using block to transmit data in OC, and we use closure to transmit data in Swift.

This is my file directory.

Quick research-project catalogue.

AppDelegate.swift

myViewController.swift

ViewController.swift

Network-network correlation.

Requesting client. swift

RequestAPI.swift

Custom vc- encapsulated VC,

CostomNavigationVC.swift

BaseViewController.swift

Here we mainly use the API of China Weather Network to test a PUT request, and look at RequestAPI.swift.

Override func viewDidLoad() {

super.viewDidLoad()

self . view . background color = ui color . brown color()

Var image: UIImage

//Customize the back button on the left side of //Navigationbar, and refer to the BaseViewController.swift file.

Self. leftbutton (nil,hli image: nil,title:“return”,size: cgsize (width: 38,height: 30),action:“button click”,target: self)。

var dic:Dictionary= ["A":"a "," B":"b "," C ":" C "];

//After the test

RequestAPI。 POST("List ",body: dic,succeed: succeed,failed:failed)

//Get the test

var getUrl:String = "/Atad/ 10 1 190 10 1 . html "

RequestAPI。 GET(getUrl,body: nil,succeed: succeed,failed: failed)

//File upload

//Make any additional settings after loading the view.

}

func succeed(task:NSURLSessionDataTask! ,responseObject:AnyObject! )-& gt; Invalid {

Println ("Oh, my God succeeded +\(responseObject)")

}

Func failed (task: NSURLSessionDataTask! , error: NSError! )-& gt; Invalid {

Println ("Oh, damn failure")

}

In ViewController, we GET data by calling the class method get of RequestAPI. At the same time, we define two methods: success and failure. Note 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. Call the get method of equestAPI to pass a function pointer, and the data will be returned through the function pointer after the network request is successful.

Then we can do other work.

Errors of 3084101and10/6 are often encountered after using the new version of AFNetworking. These errors are usually data parsing errors. Just change the corresponding data type in AFNetworking, or you can define it yourself according to the actual situation.

/**

request client . shared instance . request serializer = AFJSONRequestSerializer()

request client . shared instance . responseserializer = afjsonresponserializer()

request client . shared instance . request serializer . setvalue(" application/JSON,text/html ",forHTTPHeaderField: "Accept ")

request client . shared instance . request serializer . setvalue(" application/JSON; charset=utf-8 ",forHTTPHeaderField:" Content-Type ")

*/

In a word, AFNetworking is the most widely used network framework. By further simple external encapsulation of AFNetworking, a lot of initialization work can be avoided when network requests are made, and singletons are directly used, which improves efficiency.

Efficiency, but also save a lot of code, at least at first glance, I look more comfortable. By encapsulating AFNetworking with swift, we are also familiar with the basic syntax, data types, singletons and closures of Swift.

For swift beginners, the actual learning effect is quite obvious. With this, you can now write a simple advertisement or news with swift. What are you waiting for? As long as you rush forward, you won't end up.