iOS development: using afnetworking in Swift

Source: Internet
Author: User
Tags file upload json

Today is a brief talk on how to use the more popular Afnetworking request framework in Swift Engineering.

Since afnetworking currently does not have a swift version, our project uses Cocoapod to install afnetworking.

This is my prodfile file, the use of cocoapod is the same as the use of OC is the same time, in order to facilitate the project, we randomly create a class, select the language OC, We will find that the project will come out with a swiftstudy-bridging-header.h file that deletes the created OC class, introduced here

OK, 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 '

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

Use the new version afnetworking know it has a afhttpsessionmanager, where we inherit Afhttpsessionmanager use Singleton mode to return an instance of the class,

To do a network operation the single example in Swift is very different from OC syntax, and swift syntax is not much explained 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. li>     
    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 appropriate baseurl to  
    12.             var url:nsurl = nsurl (string:   "")! 
    13.            static.instance  = requestclient (Baseurl: url)  
    14.        })   &NBSP
    15.          //Returns an instance of this class  
    16.         return static.instance! 
    17.           
    18.    } 

With the example of requestclient, we can post, get, and upload image files to the package.

Use afnetworking in OC to use block for data transfer and so on, in swift we use closures for data transmission

This is my file directory.

Swiftstudy------------Engineering Catalogue

Appdelegate.swift

Myviewcontroller.swift

Viewcontroller.swift

Network------------Network related

Requestclient.swift

Requestapi.swift

CUSTOMVC------------VC Encapsulation,

Costomnavigationvc.swift

Baseviewcontroller.swift

Here we mainly take the Chinese Weather Network API test A put request, look at the requestapi.swift.

    1. override func viewdidload ()  { 
    2. super.viewdidload ()  
    3.  
    4. self.view.backgroundcolor = uicolor.browncolor ()  
    5. var image:uiimage  The
    6. //navigationbar  left button customization, reference file baseviewcontroller.swift 
    7. Self.leftbutton (nil,  hliimage: nil, title:  "Back",  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:&NBsp;failed)  
    17.  
    18. //File upload  
    19. // do any additional setup& nbsp;after loading the view. 
    20. func succeed (Task: nsurlsessiondatatask!,responseobject:anyobject!) ->void{ 
    21. println ("oh my god  succeeded + (Responseobject)")  
    22.  
    23. func failed (task:nsurlsessiondatatask!,error:nserror!) ->void{ 
    24. println ("oh shit  failed")  

In Viewcontroller we get the data by calling Requestapi's class method gets, and we define two methods succeed and failed, and look at the parameters in the method and the Afhttpsessionmanager

The parameter of the return data is the same, so that we get the data is the server to return all the data, call Equestapi get method will speak a function pointer passed past, the network request after the success of the function pointer will return the data.

Then we can do other work.

Use of the new version of Afnetworking will often encounter 3084 1011 and 1016 errors, the occurrence of these errors is generally a data parsing error, change the corresponding data types within the afnetworking can also be defined according to the 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 using the most network framework, the further simple outer encapsulation of afnetworking, we can avoid the network request when a lot of initialization work, directly use a single example can, this improves

Efficiency, but also save a lot of code, at least a look at their own looks more comfortable, by using Swift to encapsulate afnetworking, but also systematically familiar with Swift's basic syntax, data types, as well as a single case, closures, etc. to use,

For Swift beginners, the actual learning effect is still more obvious, with these now you can use Swift to write a simple embarrassing hundred or news, and so on what that, as long as their own forward, it will not be the last.

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.