swift-Basic Learning for Network request (HTTP)

Source: Internet
Author: User

Swift initiates a network request that naturally has his own processing class nsurlrequest. This is the same as httpclient in Android. So this blog is just a record of the process, the code is relatively simple.

 Import UIKitProtocol Httpprotocol{func Didrecieveresults (results:nsdictionary)}class Httpcontroller:NSObject{var delegate:Httpprotocol? Func Onsearch(URL:String){var Nsurl:Nsurl=Nsurl(string:URL)! var request:nsurlrequest=nsurlrequest(URL:nsurl)        nsurlconnection. sendasynchronousrequest(request, queue: nsoperationqueue.  Mainqueue(), completionhandler:{(response:nsurlresponse!,data:nsdata!,error:nserror!)-Voidin Var Jsonresult:nsdictionary=nsjsonserialization.Jsonobjectwithdata(data, options: nsjsonreadingoptions.  Mutablecontainers, error: nil)as!nsdictionarySelf.delegate?. Didrecieveresults(jsonresult)})    }}

This encapsulates a Httpcontroller class for processing requests. When this request is handled asynchronously, it's worth noting that I wrote a delegate class to data callbacks. So we can process our data in Viewcontroller. Viewcontroller as the name implies is a controller, in order to follow the MVC principle, we should not write too much logic code in the controller, can be handed to the model layer to come out, the controller is responsible for the call can be. This makes the code much easier to read. Scalability.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

swift-Basic Learning for Network request (HTTP)

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.