美文网首页iOS技术及开发讨论iOS Developer程序员
我的第一个半swift工程,含afn二次封装

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

作者: 扶摇先生 | 来源:发表于2016-11-20 19:31 被阅读216次

我是个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.
    }


}

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

相关文章

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

    我是个swift初探者,至于我为什么称这个工程为半swift工程,因为这个工程并不是我一点点用swift写出来的,...

  • swift 封装AFN

    import UIKitimport AFNetworkingenum WBReqMethod { case ge...

  • iOS-网络相关

    本篇涵盖AFN、ASI、封装网络请求等. 1.iOS网络请求之ASI与AFN的二次封装及意义2.LXNetwork...

  • AFNetWorking 封装

    背景:关于AFN的封装问题是每一个项目都需要的,如果看到那么多的重复代码会疯。so 写了一个swift的AFN封装...

  • Swift之AFN封装

    看着视频敲swift,人家封装了一个AFN的方法,我跟着封装,结果出错了,原因我目前还不知道,不过我改了下终于改对...

  • Swift AFN简单封装

    封装 使用

  • swift封装AFNetworking

    以前自己用swift封装的AFN,封装成工具类直接拖就能用 首先把工具类设计成单例对象 然后自己封装了网络请求方法

  • Alamofire4.4 在swift3 项目中的使用

    最近刚接手swift3和OC混编的项目,项目比较乱,由于网络请求的工具类是上一个人基于AFN二次封装的,在swif...

  • AFN 二次封装

    .打开下载下来的demo,运行如下(其中红色箭头所指的文件是我们拖到项目中的两个文件): 1678515-d4b8...

  • HYBNetworking阅读笔记

    如题:本篇是对于HYBNetworking的阅读学习笔记 HYBNetworking是基于AFN 的二次封装,1....

网友评论

    本文标题:我的第一个半swift工程,含afn二次封装

    本文链接:https://www.haomeiwen.com/subject/fysypttx.html