2019-01-20 13:39:02 qq_43656530 阅读数 207

在这里插入图片描述

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    //底部标签控制器
    let oneNav = UINavigationController(rootViewController: OneVC())
    oneNav.tabBarItem = UITabBarItem(title: "首页", image: UIImage(named: "dongTai"), selectedImage: UIImage(named: "dongTai_H"))
    
    let twoNav = UINavigationController(rootViewController: VCTwo())
    twoNav.tabBarItem = UITabBarItem(title: "微淘", image: UIImage(named: "dongTai"), selectedImage: UIImage(named: "dongTai_H"))
    
    let threeNav = UINavigationController(rootViewController: ThreeVC())
    threeNav.tabBarItem = UITabBarItem(title: "消息", image: UIImage(named: "dongTai"), selectedImage: UIImage(named: "dongTai_H"))
    
    let fourNav = UINavigationController(rootViewController: FourVC())
    fourNav.tabBarItem = UITabBarItem(title: "购物车", image: UIImage(named: "dongTai"), selectedImage: UIImage(named: "dongTai_H"))
    let fiveNav = UINavigationController(rootViewController: FiveVC())
    fiveNav.tabBarItem = UITabBarItem(title: "我的", image: UIImage(named: "dongTai"), selectedImage: UIImage(named: "dongTai_H"))
    
    let tbv = UITabBarController()
    tbv.viewControllers = [oneNav,twoNav,threeNav,fourNav,fiveNav]
    tbv.selectedViewController = twoNav
    window?.rootViewController = tbv
    
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

import UIKit

class VCTwo: UIViewController {

private lazy var pageTitleView: MFPageTitleView = {
    let config = MFPageTitleViewConfig()
    config.titleColor = colorWithRGB(r: 43, g: 43, b: 43)
    config.titleSelectedColor = colorWithRGB(r: 211, g: 0, b: 0)
    config.titleFont = UIFont.systemFont(ofSize: 14, weight: .regular)
    config.indicatorColor = colorWithRGB(r: 211, g: 0, b: 0)
    let pageTitleView = MFPageTitleView(frame: CGRect(x: 0, y: navHeight, width: SCREEN_WIDTH, height: 41), titles: ["全部", "上新", "视频直播", "特别关注", "达人"], config: config)
    pageTitleView.pageTitleViewDelegate = self
    return pageTitleView
}()

private lazy var pageContentView: MFPageContentView = {
    var childControllers = [UIViewController]()
    for k in 0..<5 {
        var vc = UIViewController()
        let red: CGFloat = CGFloat(arc4random() % 256)
        let green: CGFloat = CGFloat(arc4random() % 256)
        let blue: CGFloat = CGFloat(arc4random() % 256)
        vc.view.backgroundColor = UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: 1.0)
        if k==4{
            vc = WeiTaoVC()
        }
        childControllers.append(vc)
    }
    
    let pageContentViewY = pageTitleView.frame.maxY
    let pageContentView = MFPageContentView(frame: CGRect(x: 0, y: pageContentViewY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-pageContentViewY), parentVC: self, childVCs: childControllers)
    pageContentView.pageContentViewDelegate = self
    return pageContentView
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white
    
    view.addSubview(pageTitleView)
    view.addSubview(pageContentView)

}

}

extension VCTwo: MFPageTitleViewDelegate, MFPageContentViewDelegate {
func selectedIndexInPageTitleView(pageTitleView: MFPageTitleView, selectedIndex: Int) {
self.pageContentView.setPageContentViewCurrentIndex(currentIndex: selectedIndex)
}
func pageContentViewScroll(progress: CGFloat, originalIndex: Int, targetIndex: Int) {
self.pageTitleView.setPageTitleView(progress: progress, originalIndex: originalIndex, targetIndex: targetIndex)
}
}

import UIKit

class WeiTaoVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

let mArr:NSMutableArray = []
var cellHight:CGFloat = 0
var tv:UITableView?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    
     NotificationCenter.default.addObserver(self, selector: #selector(test), name: NSNotification.Name(rawValue:"cellHight"), object: nil)
    
    view.backgroundColor = UIColor.white
    
    let path = Bundle.main.path(forResource: "daren", ofType: "json")
    let url = URL(fileURLWithPath: path!)
    
    do {
        let data = try Data(contentsOf: url)
        let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
        // print(jsonData)
        let jsonArr:NSArray = jsonData as! NSArray
        print(jsonArr)
        
        for item in jsonArr {
            
            let k:NSDictionary = item as! NSDictionary
            
            if k.object(forKey: "type") as! String == "0"{
                
                let md:OneMD = OneMD(headImg: k.object(forKey: "head") as! String, title: k.object(forKey: "title") as! String, detailTitle: k.object(forKey: "detailTitle") as! String, img: k.object(forKey: "img") as! String, time: k.object(forKey: "time") as! String, num: k.object(forKey: "num") as! String, type: k.object(forKey: "type") as! String)
                mArr.add(md)
                
            }else if k.object(forKey: "type") as! String == "1" {
                
                let md:TwoMD = TwoMD(headImg: k.object(forKey: "head") as! String, title: k.object(forKey: "title") as! String, detailTitle: k.object(forKey: "detailTitle") as! String, img: k.object(forKey: "img") as! NSMutableArray, time: k.object(forKey: "time") as! String, num: k.object(forKey: "num") as! String, type: k.object(forKey: "type") as! String)
                mArr.add(md)
            }else{
                let md:ThreeMD = ThreeMD(headImg: k.object(forKey: "head") as! String, title: k.object(forKey: "title") as! String, detailTitle: k.object(forKey: "detailTitle") as! String, img: k.object(forKey: "img") as! String, time: k.object(forKey: "time") as! String, num: k.object(forKey: "num") as! String, type: k.object(forKey: "type") as! String)
                mArr.add(md)
            }
            
        }
        
        
        
    } catch let error as Error? {
        print(error as Any)
    }
    
    
    tv = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height-120), style: .plain)
    view.addSubview(tv!)
    
    tv!.delegate = self
    tv!.dataSource = self
    
    tv!.register(UINib(nibName: "OneCell", bundle: Bundle.main), forCellReuseIdentifier: "cell1")
    tv?.register(UINib(nibName: "TwoCell", bundle: Bundle.main), forCellReuseIdentifier: "cell2")
    tv!.register(UINib(nibName: "ThreeCell", bundle: Bundle.main), forCellReuseIdentifier: "cell3")
    
    tv!.tableFooterView = UIView()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return mArr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let item = mArr[indexPath.row]
    
    if item is OneMD{
        let md:OneMD = mArr[indexPath.row] as! OneMD
        
        let cell:OneCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! OneCell
        cell.setCellWithData(model: md)
        return cell
    } else if item is TwoMD{
        let md:TwoMD = mArr[indexPath.row] as! TwoMD
        
        let cell:TwoCell = tableView.dequeueReusableCell(withIdentifier: "cell2") as! TwoCell
        cell.setCellWithData(model: md)
        print(cellHight)
        return cell
    }else{
        let md:ThreeMD = mArr[indexPath.row] as! ThreeMD
        
        let cell:ThreeCell = tableView.dequeueReusableCell(withIdentifier: "cell3") as! ThreeCell
        cell.setCellWithData(model: md)
        return cell
    }
    
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
    let item = mArr[indexPath.row]
    
    if item is TwoMD{
         return cellHight+10
        
    } else{
        
        return 200
    }
}

@objc func test(nofi : Notification){
    
    cellHight = nofi.userInfo!["post"] as! CGFloat
    tv?.reloadData()
    /// 移除通知
    NotificationCenter.default.removeObserver(self)
}

}

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    let path = Bundle.main.path(forResource: "daren", ofType: "json")
    let url = URL(fileURLWithPath: path!)
    
    do {
          let data = try Data(contentsOf: url)
          let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
         // print(jsonData)
          let jsonDic:NSArray = jsonData as! NSArray
          print(jsonDic)
        
        
        
        
    } catch let error as Error? {
          print(error as Any)
    }

}

}

2016-02-02 11:54:50 henanzhg 阅读数 540

      JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。同时也具有很好的快平台性。

           从iOS开发的角度来说,JSON更多的可以看作是一种包含很多键值对的对象。首先我从www.k780.com这个网站中得到一个实时天气情况接口。


       这个链接直接在浏览器中打开后显示效果是这样的:

{"success":"1","result":{"weaid":"1","days":"2016-02-02","week":"星期二","cityno":"beijing","citynm":"北京","cityid":"101010100","temperature":"5℃/-7℃","temperature_curr":"1℃","humidity":"22%","weather":"晴","weather_icon":"http://api.k780.com:88/upload/weather/d/0.gif","weather_icon1":"","wind":"东北风","winp":"2级","temp_high":"5","temp_low":"-7","temp_curr":"1","humi_high":"0","humi_low":"0","weatid":"1","weatid1":"","windid":"13","winpid":"203"}}

       看起来比较乱,但是大致可以看到很多的键值对,我们将这个内容用在线JSON编辑器打开之后,效果是这样的:



       这样显得清晰多了。

       那么如何在Swift工程里对这个URL进行解析呢?
       用Xcode创建一个Single View Application。在Info.plist中添加App Transport Security Settings选项,选项中添加Allow Arbitrary Loads并将Value设置为YES。(这么做的原因在我以前的文章中有写,这里不再解释)
       对JSON解析,我们需要用到NSJSONSerialization。我现在用的是Xcode7.2。代码截图如下:



       我看过一些教程,因为相对时间比较靠前,他们的NSJSONSerialization.JSONObjectWithData的方法还有一个参数error,在新版本的Xcode中,这个参数已经没有了,而且NSJSONReadingOptions的参数也发生了一些改变,因此,目前必须要要做try这个操作来解决 
error:Call can throw, but it is not marked with 'try' and the error is not handled 这个编译错误 

输出结果:




这样你就可以通过objectForKey去取值了。


2016-10-31 14:55:30 qq_31292239 阅读数 155

let result = String.init(data: data!, encoding: NSUTF8StringEncoding)

                    

                    let data = (result?.dataUsingEncoding(NSUTF8StringEncoding)!)! as NSData

                    let facusData = try?NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)

                    

                    let dic = facusData!

//result 为获取的Json字符串

//最后的dic 是解析出来的字典

2015-06-16 21:42:18 swiftlab 阅读数 11

JSONCodable:基于 Swift 2.0 新特性(Protocol Extensions and Error Handling)的JSON 解析类。

2016-02-27 15:06:20 Too_greedy 阅读数 1354
这里讲解的是json字符串解析.寻常解析用三方库即可.但是有时,解析出来的数据并不是你想要的.
例如返回的数据为一个数组,但是却用json字符串包装的.那么你用原生的或三方库解析出来的数据为一个字符串类型:
[
"http://www.example.com/uploads/7186d834f55e9bd95754b12ebe6df911.jpg",
"http://www.example.com/uploads/8bd827dae398640c198f991fe7a877bb.jpg"
]

  这里用Swift代码.及解析出来的类型为String类型,本来想用的是数组,但是String缺无法转化为Array类型,我试过去掉两边中括号,并用 “逗号” 分割开.但是没有成功. 这时就需要进一步把解析出的Stirng再解析成数组

    //例如的数据,用一个常量imageJSONStr来接收的  
     let imageJSONStr = "[
"http://www.zhuluoxi.com/uploads/7186d834f55e9bd95754b12ebe6df911.jpg",
"http://www.zhuluoxi.com/uploads/8bd827dae398640c198f991fe7a877bb.jpg"
]"  
     let images = Array<String>() //用来接收解析完成的数组  
        //字符串编码成json数据
        let data:NSData = imageJsonStr.dataUsingEncoding(NSUTF8StringEncoding)!
        var img: AnyObject? 
        do{    //解析json类型数组
            try img = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        }catch let error as NSError{
            print("error: \(error)")
        }
        images = img as! Array<String>

ok,搞定,images 就是你想要的最终的数组
再来个终极版的,用extension解决,一劳永逸,使用时,一句代码搞定:

extension String {

    var parseJSONString: AnyObject? {
        var any: AnyObject?
        let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        do{
            any = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
        }catch let error as NSError{
            print("error: \(error)")
        }
        return any
    }
}

使用时这样:

    let imageJSONStr = "[
"http://www.zhuluoxi.com/uploads/7186d834f55e9bd95754b12ebe6df911.jpg",
"http://www.zhuluoxi.com/uploads/8bd827dae398640c198f991fe7a877bb.jpg"
]"
    let images: Array<String> = imageJSONStr.parseJSONString as! Array<String>      

搞定.一句代码解决.而别别人也可以使用这个方法了.

  最后有个小问题,对于上面extension中的do catch 方法中,不能直接return,哪位高手可以指点小弟一下怎么做,不用 “any” 这个临时变量,直接在do括号中返回

没有更多推荐了,返回首页