Swift Tutorial 16-using Swift to call afnetworking for network requests

Source: Internet
Author: User

How do I use Swift for network requests?

We first create a swift project, the project name is Swiftdemo

Then create a new OC class in the project, and Xcode will ask if you are creating a Swiftdemo-bridging-header.h file that bridges OC and Swift

Select Yes to generate the project name-bridging-header.h file, in which we introduce the OC framework corresponding to the header file can be implemented in the SWIFT Project call OC Code

The current afnetworking framework is written by OC, we want to use AF in swift, you need to import "AFNetworking.h" in the Bridging-header.h file

The effect is as follows:




The simplest AF GET request

afrequesttest.swift//swiftdemo////Created by Mbinyang on 15/4/9.//Copyright (c) 2015 Cc.huanyouwang.  All rights Reserved.//import Uikitclass Afrequesttest:nsobject {func afrequesttest () {var Paramdict = ["Access_token": "2.00hze3af0gvjsm551ca8e0920nf13n", "UID": "5117873025"] var Afmanager = Afhttprequesto Perationmanager () var op = afmanager.get ("http://lovemyqq.sinaapp.com/getState.php", Parameters:paramdi                                CT, Success: {(operation:afhttprequestoperation!, responseobject:anyobject!) in var arr:anyobject! = Nsjsonserialization.jsonobjectwithdata (Responseobject as NSData, Options:NSJSONReadingOptions.AllowFragments,                                Error:nil)//print array or dictionary element println (arr!)                        Avoid strong reference loops unowned var unself:afrequesttest = self//self.xxx        Operation}, Failure: {(operation:afhttprequestoperation!, error:nserror!) in println ("Request error:" + error.localizeddescription) unowned var unself:afreq Uesttest = self//self.xxx operation//error related operation}) Op.responseserializer = Afht Tpresponseserializer () Op.start ()}}


Call the network request in a Viewcontroller viewdidload to test


    Override Func Viewdidload ()    {        super.viewdidload ()                        afrequesttest (). Afrequesttest ()    }


Output:

{result = ({state = {address = "\u4e2d\u56fd\u5317\u4eac\u                5e02\u671d\u9633\u533a\u5efa\u5916\u8857\u9053\u5efa\u56fd\u8def100\u53f7 ";                Content = "\u4f60\u662f";                Date = "2015-01-07 19:06:13";                Fromuid = 5117873025;                id = 6664;                Image = "Http://xuyingtest-xuyingttt.stor.sinaapp.com/1420628745userImage.png";                Imagecount = 1;                Latitude = "39.907007";            Longitude = "116.470241";        }; }, {state = {address = "\u4e2d\u56fd\u5317\u4eac\u5e02\u77f3\u666f\                u5c71\u533a\u53e4\u57ce\u8857\u9053 ";                Content = "\U516C\U79EF\U91D1";                Date = "2014-11-23 11:10:57";                Fromuid = 5117873025;                id = 5593;                Image = "Http://xuyingtest-xuyingttt.stor.sinaapp.com/1416712253userImage.png"; IMagecount = 1;                Latitude = "39.897711";            Longitude = "116.184322";        };                }, {state = {address = "";                Content = Chen;                Date = "2014-11-21 11:02:19";                Fromuid = 5117873025;                id = 5551;                Image = "Http://xuyingtest-xuyingttt.stor.sinaapp.com/1416538936userImage.png";                Imagecount = 1;                Latitude = "";            longitude = "";        };    }    ); Success = 0;}


Precautions and instructions:

1.Swift and OC call methods in different forms, OC is a space, Swift is the dot number


2.Swift Network request closures and OC notation are not the same as described in


Swift Tutorial 15-Closure block multiple application methods

Swift Tutorial 14-func function, Function type _ vs OC


3. Avoid statements that strongly refer to loops


unowned var unself:afrequesttest = self

No primary reference, no increase in reference count;

Or

Weak Var self2:afrequesttest! = Self

A weak reference, and does not increase the reference count, but returns an optional type that can be nil

4. Type conversion, down transformation

Responseobject as NSData

Down type conversion, using as or as? ;

The difference is as? Conversion failure will return nil; successful return optional type


5. Constructors and java/c++ and similar

Afrequesttest (). Afrequesttest ()

Swift's constructor is equivalent to the Alloc init of OC, which is used for initialization.

But Swift's constructor is init () Other languages are class names

Follow-up articles on Swift constructors and other object-oriented articles will be logged in succession

6. JSON parsing without the use of AF

Op.responseserializer = Afhttpresponseserializer ()

JSON parsing for afnetwoking may fail parsing for some interfaces, resulting in error output

Error:request failed:unacceptable content-type:text/html


At this point we just add the face code, we can not let AF help us to parse, and the use of the system's own JSON parsing


Similar to the 7.Post request, the above code provides a test interface



Swift Series Tutorial: http://blog.csdn.net/yangbingbinga/article/category/3050845








Swift Tutorial 16-using Swift to call afnetworking for network requests

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.