IOS: protocol in Swift and its application instance, iosswift

Source: Internet
Author: User

IOS: protocol in Swift and its application instance, iosswift

I recently encountered a variety of repeated code issues when I learned how to capture webpage content in ios. Looking at so many repeated code, I felt really uncomfortable. So I learned the ios protocol.

In my opinion, this protocol is actually an interface in Java.

That is to say, define a protocol (or interface), define a bunch of methods, and pass in the instances of classes that implement the method.


In my project, the viewcontroller that captures different web pages and obtains the code of the web page is exactly the same. Except for different web pages, this part is extracted as a class, this function is used to retrieve data from the Internet and notify viewcontroller when the data is retrieved. In this case, a callback is required. Here we use protocol to achieve this goal.


First define a protocol

@objc protocol callBack : NSObjectProtocol {    func success(data:String)    optional func error(error: NSError)}

The protocol is called callBack, which defines two methods, one of which is optional.

Define a class to capture webpages

class NetUtil :NSObject, NSURLConnectionDelegate,NSURLConnectionDataDelegate{    var cb :callBack?    init(url:String,cb:callBack) {        super.init()        self.cb = cb        let req : NSURLRequest = NSURLRequest(URL: NSURL(string: url)!)        let conn : NSURLConnection = NSURLConnection(request: req, delegate: self)!    }    var data : NSMutableData!    var tableData: NSArray = NSArray()    func connection(connection: NSURLConnection, didReceiveData data: NSData) {        self.data.appendData(data);    }    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {        self.data = NSMutableData();    }        func connectionDidFinishLoading(connection: NSURLConnection) {        let s = NSString(data: data, encoding: NSUTF8StringEncoding)        cb?.success(s!)    }    func connection(connection: NSURLConnection, didFailWithError error: NSError) {        cb?.error?(error)    }}

I call it a network tool. Because NSURLConnection is used to retrieve data, this class also needs to implement two NSURLConnection protocols, then call the callBack method in the corresponding method to notify the main program to complete the corresponding work.

After successful call, cb. success () is called. After an error occurs, cb. error () is called ().

After these parameters are ready, return to the corresponding viewcontroller to implement the callBack protocol and call it.

//// ViewController. swift // test project /// Created by Zhou Mi on 14/11/26. // Copyright (c) 2014 www.miw.cn. all rights reserved. // import UIKitclass ViewController: UIViewController, callBack {override func viewDidLoad () {super. viewDidLoad () var url: String! = "Http://www.miw.cn/info/csdn/cloud/1/list" // call my network tool here, using self as the parameter NetUtil (url: url, cb: self) implementing the callBack Protocol} @ IBOutlet weak var appsTableView: UITableView! Override func didReceiveMemoryWarning () {super. didReceiveMemoryWarning ()} // The necessary method func success (data: String) {println (data)} In callBack is implemented here )}}

Now it seems that my main program is much simpler?

You can process the obtained data in the success method.

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.