Swift Base demo contains refresh, load, network request, MVC

Source: Internet
Author: User
Tags closure

Swift has a alamofire third party is making a request for the network, it is written by the author of the Swift form of afnetworking, today first introduced, using Pod to import Afnetworking,svprogresshud, Mjrefresh and other third-party implementation to refresh data, load more, network requests, while using the MVC model for interface Building, then study the function of Alamofire network request, and then share to everyone ....

This article has two interfaces, the first interface directly uses the afnetworking to make the network request, then the interface displays

The first interface creates the table:

Self.mytableview = Uitableview.init (Frame:CGRect.init (x:0, y:0, Width:screen_w, Height:screen_h), style:uitableviews Tyle.plain);
Self.myTableView.delegate = self;
Self.myTableView.dataSource = self;
Self.myTableView.rowHeight = 80;
Self.myTableView.tableHeaderView = Uiview.init ();
Self.myTableView.tableFooterView = Uiview.init ();
Self.view.addSubview (Self.mytableview);
Register cell
Self.myTableView.register (mycelltableviewcell.self, Forcellreuseidentifier: "MyCell");
NIB Registration
Self.tableView.registerNib (uinib (nibname: "Mycelltableviewcell", Bundle:nil), Forcellreuseidentifier: "MyCell")
Add drop-down refresh
Self.myTableView.mj_header = Mjrefreshnormalheader (refreshingblock: {
Data loading
Self.pageindexi = 1;
Self.datahttprequest (PageIndexStr:NSString.init (format: "%d", Self.pageindexi));
});
Set Startup to refresh
Self.myTableView.mj_header.beginRefreshing ();

Then make the network request method:

MARK:-------afnetworking basic Data Request form (not encapsulated method)
Func datahttprequest (pageindexstr:nsstring) {

Svprogresshud.show (withstatus: "Loading");
If Pageindexstr.isequal (to: "1") {
Self.dataArray.removeAllObjects ();
}

Let urlstr = "http://www.healthmanage.cn/android/hrsBabyAction_loadHrsBabyHealth.action";
Let paramsdic = ["UserId": "38567", "pagesize": "8", "PageIndex":p ageindexstr];

Afnetworking using POST requests
Let SessionManager = Afhttpsessionmanager.init ();
SessionManager.responseSerializer.acceptableContentTypes?. Insert ("Text/plain");
Sessionmanager.post (Urlstr, Parameters:paramsdic, Progress:nil, Success: {(_, Responseobject), Void in
Print ("Output data request results at this time ... \ (responseobject)");

Svprogresshud.dismiss (withdelay:1);
Self.myTableView.mj_header.endRefreshing ();
Guard statement, used to determine when a condition is not met and exits safely, not crash
Guard (Responseobject as?) nsdictionary)! = Nil else{
Print ("The return data is nil, or the type does not match");
Return
};
Let Resultdic = Responseobject as! Nsdictionary;
Let SUCCESSB = resultdic["Success"] as! Bool;
if (SUCCESSB) {
If a value is returned
Let ItemArray = resultdic["ITEMS"] as! Nsarray;

if (self.myTableView.mj_footer! = nil)
{
Self.myTableView.mj_footer.endRefreshing ();
}
Else
{
Determine the number of arrays and page, add pull-up load if eligible
if (Itemarray.count = = 8 && pageindexstr.isequal (to: "1"))
{
Self.myTableView.mj_footer = Mjrefreshbacknormalfooter (refreshingblock:{(), Void in

Self.pageindexi = self.pageindexi+1;
Self.datahttprequest (PageIndexStr:NSString.init (format: "%d", Self.pageindexi));
})
}
}

For DiC in ItemArray {
Because the array is: [String:anyobject] Dictionary type, you cannot use as. Nsdictionary, I understand that, I don't know, right?
Let Itemdic = dic as! [String:anyobject];
Self.dataArray.add (Itemdic);
}
Self.myTableView.reloadData ();
}
Else
{
Request no data novalue situation
If self.dataarray.count>0{
Self.myTableView.mj_footer.endRefreshing ();
Self.myTableView.mj_footer = nil;
}
}
}) {(_, error) in
Print ("Request data error Report ... \ (error)");
Svprogresshud.showerror (withstatus: "Network request Error");
}

After the first interface is finished, the second layer of the interface is designed using the MVC structure for style creation:


Create a tabular interface, then use the Data Request tool and model to parse the data, then display the model data in the cell

Data Request Tool Method:

Tool methods for creating request data
Parameter description: mtype: Mode urlstring:url parametersdic: Parameter success: Successful closure structure failure: failure closure structure
Func Urlrequesttool (mtype:methodtypes,urlstring:string,parametersdic:dictionary<string,any>?, Successcomplete: @escaping successclosure,failurecomplete: @escaping failureclosure) {
Svprogresshud.show (withstatus: "Loading");
if mtype = =. GET {
Self.get (URLString, Parameters:parametersdic, Progress:nil, Success: {(_, Respdata), Void in
Return data
Svprogresshud.dismiss (withdelay:1);
Successcomplete (Respdata);
}, Failure: {(_, Err) in
return error
Svprogresshud.dismiss (withdelay:1);
Failurecomplete (ERR);
})
}else{
Self.post (URLString, Parameters:parametersdic, Progress:nil, Success: {(_, Respdata) in
Return data
Svprogresshud.dismiss (withdelay:1);
Successcomplete (Respdata);
}, Failure: {(_, Err) in
return error
Svprogresshud.dismiss (withdelay:1);
Failurecomplete (ERR);
})
}
}

Model class:

Class Mydic:nsobject {
var petnamestr:string!;
var genderidstr:string!;
var birthdaystr:string!;

Init (Dict:[string:anyobject]) {
Super.init ();
Self.petnamestr = dict["PetName"] as! string!;
Self.genderidstr = dict["Genderid"] as! string!;
Self.birthdaystr = dict["Birthday"] as! string!;
}
}

Data Display in cell:
Func Setmydicmodel (Datamodel:mydic)
{
Self.nameLabel.text = Datamodel.petnamestr;
Let Sexstr = datamodel.genderidstr;//can also be turned into nsstring use
NSString has a method isequaltostring method used to determine whether two strings are exactly equal, string does not have this method, but because string is a value type, you can use = = to determine whether it is exactly equal.
if sexstr = = "1" {
Self.sexImgView.image = Uiimage.init (named: "Baby_sex_boy");
Self.headImgView.image = Uiimage.init (named: "Baby_default_boy");
}
Else
{
Self.sexImgView.image = Uiimage.init (named: "Baby_sex_girl");
Self.headImgView.image = Uiimage.init (named: "Baby_default_girl");
}

Self.birthDayLabel.text = nsstring.init (format: "Birthday:%@", datamodel.birthdaystr) as String;
}

Effect Diagram:


Specific code to see the source text comments, if not bad please praise, thank you, reproduced please indicate the source .... : Https://github.com/hbblzjy/Swift-RefreshHTTP.git



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.