Swift网络请求于数据解析简单封装

首先新建一个新工程


选择Swift语言





看到生成的ViewController 将它删除了  然后自己建一个试图控制器 继承于UITableVIewController

再建一个继承与NSObject的数据请求类,建成后就是下面结构 (名称可以自己定)


在storyboard里指定一下类和cell的重用标识符 ,以及添加跟视图

指定rootviewcoller

指定cell的重用标示符

指定好后好后运行一下看看页面是否有错误,


下面开始网络请求 以及数据解析

import UIKit
typealias senderData = (data:AnyObject)->()
class GetDataWithJson: NSObject {
    //声明一个Block
    var FinishBlock: senderData?
   
    var HTTPsendRequest = NSHTTPURLResponse();
    func connection(url:NSString,senserdata:senderData?) {
       self.FinishBlock = senserdata
        let request :NSURLRequest = NSURLRequest(URL: NSURL(string: url)!);
               dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
                NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: { (response, data, error) -> Void in
                    if (error? != nil) {
                        
                    }else{
                        
                        let jsondic:AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                        self.FinishBlock!(data: jsondic)
                    
                       
                    }
                })
               
            
        })
        
    }
    
}

import UIKit

class RootViewController: UITableViewController {
    var dataSourse = NSMutableDictionary()
    var dataArr = NSMutableArray();
    override func viewDidLoad() {
        super.viewDidLoad()
        var getdada = GetDataWithJson();
        var url = "http://127.0.0.1/SwiftServer/SwiftServer.php"
        getdada.connection(url, senserdata: { (data:AnyObject) -> () in
            self.dataSourse = data["results"] as NSMutableDictionary
            self.dataArr = self.dataSourse["newslist"] as NSMutableArray
         var dic = NSDictionary()
            for dic in self.dataArr {
              // println(dic)
            }
        
        self.tableView.reloadData()
        })
       
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return self.dataArr.count
    }

  
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("tablecell", forIndexPath: indexPath) as UITableViewCell
            cell.textLabel?.text = self.dataArr[indexPath.row].objectForKey("title") as NSString
        cell.detailTextLabel?.text = self.dataArr[indexPath.row].objectForKey("picurl") as NSString
       
        return cell
    }
   

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值