我的第一个半swift工程,含afn二次封装

我是个swift初探者,至于我为什么称这个工程为半swift工程,因为这个工程并不是我一点点用swift写出来的,而是我将我的oc代码一点点的转化为swift,而且也不涉及特别复杂的逻辑,只有一个tableView展示,过程中也遇到了一些困难,比如swift的懒加载,swift的闭包,swift的泛型数组,swift的声明等等,对于一个初探者,都是一点点抠出来的。好了不多说直接上代码,至于我说的哪些困难,在工程里也有备注。
工程的github网址https://github.com/yuyuepeng/tableViewTry 下载后需要重新设置桥接文件的路径,方法如图,可以直接桥接文件FirstTryHeader.h直接拖过去,大家哪有什么看不明白的可以在文章下面留言哦。

0F9FD48A-DAB1-4F3A-8FD1-0F2B191A1126.png

AppDelegate不多说

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow.init(frame:UIScreen.main.bounds)
let vc:ViewController = ViewController.init()
let bc:UINavigationController = UINavigationController.init(rootViewController: vc)
self.window?.rootViewController = bc
self.window?.makeKeyAndVisible()
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:.
}
}

AFNetworking的二次封装
关于这点涉及到oc和swift的混编 需要在target的build setting里的swift Compiler设置Objective-c Bridging Header ,方法自行百度。

import UIKit
//网络封装afn
class NetManager: NSObject {
//    懒加载
    lazy var netManager:AFHTTPSessionManager = {
        var netManager = AFHTTPSessionManager.init()
        var set:NSSet = NSSet.init(objects: "application/json","text/html","text/json","text/javascript","text/plain")
        netManager.responseSerializer.acceptableContentTypes = set as? Set<String>
        return netManager
    }()
//    回调方法闭包返回数据和结果
    typealias finished = (_ response:AnyObject?, _ result:String?) ->Void
    override init() {
        
    }
//    post请求
    func post(domain:String,path:String,form:NSDictionary,parameters:NSDictionary,finished: @escaping finished) -> Void {
        var url:String = String()
//        拼接url方法
        url = self.pinjie(domain: domain, path: path, parameters: parameters)
        
        netManager.post(url as String, parameters: nil, constructingBodyWith: {(_ formData: AFMultipartFormData) -> Void in
//            上传表单的参数
            self.generate(formData: formData, data: form)
            }, progress: {(_ uploadProgress: Progress) -> Void in
                
            }, success: {(_ task: URLSessionDataTask, _ responseObject: Any) -> Void in
//                以下这句代码可以根据公司的数据结构文档修改,是获取我请求的url的返回的数据
                var dict:NSDictionary = NSDictionary.init(dictionary: responseObject as! NSDictionary)
                if (dict.object(forKey: "data") != nil) {
                    var arr:NSArray = dict["data"] as! NSArray
                    finished(arr,"成功")

                }else {
                    finished(["11","11"] as AnyObject,"失败")
                }
            }, failure: {(_ task: URLSessionDataTask?, _ error: Error) -> Void in
                finished(["11","11"] as AnyObject,"失败")
        })

    }
//    拼接url
    func pinjie(domain:String,path:String,parameters:NSDictionary) -> String {
        var url = "\(domain)"
        if !path.isEmpty {
            url += path
        }
        if parameters.allKeys.count != 0 {
            if parameters.allKeys[0] as! String == "" {
                
            }else {
            url += "?"
            for key: String in parameters.allKeys as! [String] {
                var value = (parameters.value(forKey: key) as! String)
                url += "\(key)=\(value)&"
            }
            url = "\(url as NSString).substring(with: NSRange(location: 0, length: url.characters.count - 1))"
            }
        }
        return url
//        var url = "\(domain)"
//            url += path
//        
//            url += "?"
//        
//            for key: String in parameters.allKeys as! [String]{
//                var value = (parameters.value(forKey: key) as! String)
//                url += "\(key)=\(value)&"
//            }
//            url = "\(url as NSString).substring(with: NSRange(location: 0, length: url.characters.count - 1))"
//            return url
    }
     func generate(formData:AFMultipartFormData,data:NSDictionary) -> Void {
        for key in data.allKeys {
//            遍历上传
            var value = data.value(forKey: (key as? String)!)
            if value is NSDictionary {
//                如果value是字典,继续执行该方法
                self.generate(formData: formData, data: value as! NSDictionary)
            }else if value is String {
                let strValue = value as! String
                
            formData.appendPart(withForm: strValue.data(using: String.Encoding.utf8)!, name: key as! String)
            }else if value is NSData {
                let keyStr = key as! NSString
                if keyStr.contains(".") {
                    let arr:[String] = keyStr.components(separatedBy: ".")
                    if arr.last == "png" || arr.last == "jpg"||arr.last == "jpeg" || arr.last == "m4a" {
                        let typeArray = TShopTools.mineType(with: value as! Data!).components(separatedBy: "/")
                        let fileName = "\(TShopTools.uniqueString()).\(typeArray.last!)"
                        formData.appendPart(withFileData: value as! Data, name: arr[0], fileName: fileName, mimeType: TShopTools.mineType(with: value as! Data))
                    }
                }else {
                formData.appendPart(withForm: value as! Data, name: (key as! NSString) as String)
                }
            }else if value is NSArray {//value是数组
                let valueArr:NSArray = value as! NSArray
                if valueArr.firstObject is UIImage {//上传图片的数组
                    var imageData:NSData = NSData()
                    var a = 1
                    
                    for image:UIImage in valueArr as! [UIImage]{
                        if UIImagePNGRepresentation(image) == nil {
                            let imageData1:Data = UIImageJPEGRepresentation(image, 1.0)!
                            imageData = imageData1 as NSData
                        }else {
                            let imageData2:Data = UIImagePNGRepresentation(image)!
                            imageData = imageData2 as NSData
                        }
                        formData.appendPart(withFileData: imageData as Data, name: key as! String, fileName: "\(TShopTools.uniqueString())\(a).jpg", mimeType: "image/jpg")
                        a += 1
                    }
                }else {
//                    上传字符串数组
                    var i = 0
                    for stringValue: String in valueArr as! [String] {
                        print("woshi\(i)---\(stringValue)")
                        formData.appendPart(withForm: stringValue.data(using: String.Encoding.utf8)!, name: key as! String)
                        i += 1
                    }
                }
                
            }else if value is UIImage {//上传单张图片
                var imageData:NSData = NSData();
                let image = (value as! UIImage)
                if UIImagePNGRepresentation(image) == nil {
                    let imageData1:Data = UIImageJPEGRepresentation(image, 1.0)!
                    imageData = imageData1 as NSData
                }else {
                    let imageData2:Data = UIImagePNGRepresentation(image)!
                    imageData = imageData2 as NSData
                }
                formData.appendPart(withFileData: imageData as Data, name: key as! String, fileName: "\(TShopTools.uniqueString()).jpg", mimeType: "image/jpg")
            }else {
                let valueStr = value as! NSValue
                let valueStr1 = value as! NSString
                let valueStr3 = valueStr as! NSNumber
                
                if valueStr.responds(to: #selector(getter: NSNumber.stringValue)) {
                    formData.appendPart(withForm:valueStr3.stringValue.data(using: String.Encoding.utf8)! , name: key as! String)
                }else if valueStr.responds(to: #selector(NSString.data(using:))) {
                formData.appendPart(withForm: valueStr1.data(using: String.Encoding.utf8.rawValue)!, name: key as! String)
                }
            }
        }
    }
}

Model类

import UIKit

class firstModelTry: NSObject {
    var pic:String = String()
    var title:String = String()
}

cell类

import UIKit
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height


class firstCellTry: UITableViewCell {
    // 相当于oc的setModel
    var model1 : firstModelTry!
    
    var model : firstModelTry {
        set{
            self.model1 = newValue
            self.nameLabel.text = self.model1.title;
            self.backImage.sd_setImage(with: URL.init(string: self.model1.pic), placeholderImage: UIImage.init(named: "banner_placeHolder"))
        }
        get{
            return self.model1
        }
    }
    
    //懒加载创建标题label
    lazy var nameLabel: UILabel = {
        var singleLength = screenWidth/640.0
        var nameLabel = UILabel.init(frame: CGRect.init(x: 100 * singleLength, y: 300 * singleLength, width: 440 * singleLength, height: 80 * singleLength))
        nameLabel.font = UIFont.systemFont(ofSize: 15)
        nameLabel.textAlignment = NSTextAlignment.center;
        nameLabel.backgroundColor = UIColor.white
        return nameLabel
    }()
//    懒加载创建背景图
    lazy var backImage:UIImageView = {
        var singleLength = screenWidth/640.0
        var backImage = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 400 * singleLength))
        return backImage
    } ()
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        createSubViews()
    }
    fileprivate func createSubViews() {
        addSubview(backImage)
        self.backImage.addSubview(nameLabel)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

viewController里是一个tableView,里边只展示了一个图片和一个标题,需要注意的是网络封装只针对于我现在请求的这个接口,若是请求其他接口,请根据公司的接口文档自行修改。

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
    
    
//    tableView
    
    var tableView:UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: 414, height: UIScreen.main.bounds.size.height), style: UITableViewStyle.plain)
//    数据源(一个firstModelTry类型的数组)
    var dataSource:[firstModelTry] = Array()
//    单位长度
    var singleLength:CGFloat = 0.0
//    网络请求工具
    var manager:NetManager = NetManager()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = true;
        singleLength = UIScreen.main.bounds.size.width/640.0
        self.view.addSubview(tableView)
        self.title = "我的第一个swifttableView"
        tableView.delegate = self
        tableView.dataSource = self
//        加载数据源
        self.loadData()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count;
        
    }
    func loadData() -> Void {
        manager.post(domain: "http://appapi.yx.dreamore.com/index/banners", path: "", form: ["":""], parameters: ["":""]) { (_ response: AnyObject?, message: String?) -> Void in
            
//            接请求下来的数组
            let arr3:NSArray = response as! NSArray
            for dict3:NSDictionary in arr3 as! [NSDictionary]{
//                遍历得到Model
                var model3 = firstModelTry()
                model3.mj_setKeyValues(dict3)//用到mjextension
                self.dataSource.append(model3)
            }
            self.tableView.reloadData()
        }
        
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:firstCellTry = firstCellTry.init(style: UITableViewCellStyle.default, reuseIdentifier: nil)
//        创建cell
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        let model:firstModelTry = self.dataSource[indexPath.row]
//        设置Model
        cell.model = model
        return cell
        
    }
   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//    返回单元格高度
        return 400 * singleLength;
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

这就是全部代码,还希望大家能提出各种宝贵意见,以便大家互相交流,互相学习。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,019评论 4 62
  • 和你说个真实的故事,有一对夫妻,妻子在离婚的时候,她问了丈夫一句话:你到底爱过我没有?丈夫坚定的告诉了她:“不喜欢...
    丸子仙女阅读 573评论 0 0
  • 这几天看到班里面成群的女生一起玩,我总是会想起初中的我们,但不同的是,我们初中那段日子没有刻意的排斥哪个人,除了那...
    安静的女纸阅读 266评论 0 0
  • 夏天到了,林立买了双新拖鞋。翠绿的颜色加上笨拙的造型,大约是不符合绝大部分人的审美的,于是价钱极便宜。 拖鞋沾了水...
    悬诀阅读 452评论 0 2
  • ——读《大学的精神》 《奇葩说》第一季海选时,一个清华在读博士带着对未来从业的迷茫来参选,被高晓松批判其愧对名校对...
    宋染青阅读 785评论 0 2