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)