Swift上传图片,OC和Swift混编

//这个纯属有点时间,用swift开发的模块功能
//里面缺少分装的类,swift语言成熟应该没问题

//#define StatusHeight [UIApplication sharedApplication].statusBarFrame.size.height
//#define KNavgationBarHeight (StatusHeight + 44)

import UIKit

class KGCSwiftUploadVIewController: KGCBaseViewController,ZYQAssetPickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,ImagesEditViewControllerDelegate,DelegateName,UIPickerViewDelegate, UIPickerViewDataSource,UIImagePickerControllerDelegate{

var pushAgainSucsessBlock:((String) -> ())?

func methodPost(string: NSString) {
     mTableView.reloadData()
}

func method(string: NSString) {
    let topView = self.view
    topView?.makeToast("输入文字不超过50个", duration:2.0, position:CSToastPositionCenter)
    mTableView.reloadData()
}

func methodSource(string: NSString) {
   mTableView.reloadData()
}

var arrayNumber = NSMutableArray()
var mTableView:UITableView!
let arry:[String] = ["描述*:", "岗位*:", "来源 :","    "]
let heigth:CGFloat = SCREEN_WIDTH/4.9
let width:CGFloat = SCREEN_WIDTH/4.9
var roweee:Int = 0
var shareBtn:UIButton!
var mBackView:UIView!
var submitBtn:UIButton!
var arrayData = NSArray()
var imageArray = NSArray()
var pickerView:UIPickerView!
let viewBack = UIView()
var typeNumber = NSString()

public var typeString = "0"
public var one = ""
public var Two = ""
public var Three = ""
public var mID = ""
var numbjjj = 0;
var number = 0
var cellndex = ""

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.white
    mBackView = UIView()
    shareBtn = UIButton()
    self.dismissBackButton()
    self.addTitleView(withTitle:"试题上传")
    submitBtn = CreationSubBtn(title:"提交")
    submitBtn.addTarget(self, action:#selector(tap(_:)), for:.touchUpInside)
    self.view.addSubview(submitBtn)
    initTableView()
    reqeustData()
}

//MARK -- 重写方法
override func dismissView() {
    mTableView.reloadData()
    perform(#selector(mSaveData), with:self, afterDelay:0)
}

@objc func mSaveData() {

    //都为空的情况下直接返回上个界面
    if one.isEmpty && Two.isEmpty && Three.isEmpty && arrayNumber.count < 1{
        self.dismiss(animated:true, completion: {})
    }
    else{
        let alertSheet = UIActionSheet(title:"发现有编辑的内容并未提交,确认退出?", delegate: self as UIActionSheetDelegate, cancelButtonTitle:nil, destructiveButtonTitle:nil, otherButtonTitles: "去意已决", "取消")
        alertSheet.tag = 101
        alertSheet.show(in: self.view)
    }
}

func AlertSheet(str:NSString) {

// let topView = self.view
self.view?.makeToast(str as String?, duration:3.0, position:CSToastPositionCenter)
}

func initPickView() {
    viewBack.frame = CGRect(x: 0, y:SCREEN_HEIGHT*0.7, width: SCREEN_WIDTH, height:SCREEN_HEIGHT*0.3)
    viewBack.isHidden = true
    viewBack.layer.shadowColor = UIColor.red.cgColor;
    viewBack.backgroundColor =  ColorWithHexString(hex:"#96bc33")
    self.view.addSubview(viewBack)
    PickerView()
    initButton()
}

func initButton () {
    let buttonCancel = CreationDetermine(title:"取消", btnX:0)
    let Determine = CreationDetermine(title:"确定", btnX:SCREEN_WIDTH-70)
    viewBack.layer.borderWidth = 0.5
    viewBack.layer.borderColor = UIColor.lightGray.cgColor
    Determine.titleLabel?.textAlignment = .right
    buttonCancel.addTarget(self, action:#selector(ButtonCancelBtn(_:)), for:.touchUpInside)
    Determine.addTarget(self, action:#selector(DetermineBtn(_:)), for:.touchUpInside)
    viewBack.addSubview(buttonCancel)
    viewBack.addSubview(Determine)
}

func PickerView(){
    pickerView = UIPickerView()
    pickerView.frame = CGRect(x: 0, y:50, width: SCREEN_WIDTH, height:SCREEN_HEIGHT*0.3-50)
    pickerView.dataSource = self
    pickerView.delegate = self
    pickerView.selectedRow(inComponent: 0);
    pickerView.backgroundColor = UIColor.white
    viewBack.addSubview(pickerView)
}

@objc func ButtonCancelBtn(_ btnCilck:UIButton) {
     viewBack.isHidden = true
}

@objc func DetermineBtn(_ btnCilck:UIButton) {
    
    let dict = self.arrayData.object(at: 0) as! NSDictionary
    if self.Two.isEmpty {
        self.Two = (dict["name"] as? String)!
        self.number =  dict["id"] as! Int
        self.mID = String(self.number)
    }
     viewBack.isHidden = true
     mTableView.reloadData()
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1;
}

func pickerView(_ pickerView: UIPickerView,numberOfRowsInComponent component: Int) -> Int {
    return self.arrayData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,forComponent component: Int) -> String? {
    let dict = self.arrayData.object(at: row) as! NSDictionary
    return dict["name"] as? String
}

func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int)  -> CGFloat {
        return 40
 }

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    let dict = self.arrayData.object(at: row) as! NSDictionary
    Two = (dict["name"] as? String)!
    number =  dict["id"] as! Int
    self.mID = String(number)
    print("number= %d", number);
    print(dict["name"] as? String as Any)
}

func reqeustData() {
    Common.postQuestionBankRequest(withUrl:"kgc/app/getPosition", withParm:nil, success: { (respesData:Any) in
        self.arrayData = (respesData as AnyObject).object(forKey:"position") as! NSArray
        self.initPickView()
    }) { (error:Any) in
        print(error)
    }
}

func initTableView() {
    mTableView = UITableView(frame:CGRect(x:0, y:Boomheight, width:SCREEN_WIDTH, height:SCREEN_HEIGHT-64))
    mTableView.backgroundColor = UIColor.white
    mTableView.dataSource = self
    mTableView.delegate = self
    self.view.addSubview(mTableView)
    mTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
}

//设置cell的数量
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return arry.count
}

//设置section的数量
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

if  indexPath.row == 1 {
    if self.arrayData.count == 0{
        let topView = self.view
        topView?.makeToast("网络异常,请重新打开当前界面", duration:3.0, position:CSToastPositionCenter)
        return;
    }
    viewBack.isHidden = false
    UIApplication.shared.keyWindow?.endEditing(true)
  }
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
    if indexPath.row == 3
    {
        return SCREEN_HEIGHT-64-SCREEN_WIDTH/6
        
    }else{
        return SCREEN_WIDTH/6;
    }
}

//设置tableview的cell

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let indentifier = "MineCenterCell"
var cell:KGCSwiftUploadCell! = tableView.dequeueReusableCell(withIdentifier: indentifier) as? KGCSwiftUploadCell
if cell == nil {
    cell=KGCSwiftUploadCell(style: .default, reuseIdentifier: indentifier)
}

if indexPath.row == 0 || indexPath.row == 1{
    let str:NSMutableAttributedString=NSMutableAttributedString.init(string:arry[indexPath.row])
    str.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.red], range:NSMakeRange(2, 1))
    cell.textLabel?.attributedText = str
}else{
    cell.textLabel?.text = arry[indexPath.row]
}

cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.describeTextfele?.tag = 0;
cell.delegate = self
if indexPath.row == 0 {
    cell.describeTextfele?.placeholder = "涉及技术方向(最多50字)"
    cell.describeTextfele?.tag = 100;
    cell.linkLabel?.text = "50"
    if typeString == "0" {
         one = (cell.describeTextfele?.text)!
    }else{
        if (cell.describeTextfele?.text?.count)! > 0
        {
            one = (cell.describeTextfele?.text)!
        }
        cell.describeTextfele?.text = one
    }

}else if (indexPath.row == 1){
    cell.describeTextfele?.placeholder = "请选择岗位课"
    cell.describeTextfele?.isUserInteractionEnabled = false
    cell.linkLabel?.text = "请选择 >"
    cell.describeTextfele?.text = Two
    
}else if (indexPath.row == 2){
     cell.describeTextfele?.tag = 200;
     cell.describeTextfele?.placeholder = "面试的企业"
     cell.linkLabel?.text = "50"
    if typeString == "0"{
        Three = (cell.describeTextfele?.text)!
    }else{
        if (cell.describeTextfele?.text?.count)! > 0
        {
            Three = (cell.describeTextfele?.text)!
        }
        cell.describeTextfele?.text = Three
    }
}else{
    mBackView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: (cell.frame.size.width))
    cell.addSubview(mBackView)
    roweee = 0
    let screenSize:CGSize = mBackView.frame.size
    let hMargin:CGFloat = (screenSize.width - (CGFloat(4) * width)) / CGFloat((5))
    let vMargin:CGFloat = hMargin
    
    if arrayNumber.count < 9 {
        arrayNumber.add("22");
        numbjjj = 1;
    }
    
    for i in 0..

}

//MARK:处理按钮的点击事件
@objc func tappe(_ btnCilck:UIButton)
{
    let count = btnCilck.tag
    if count == 9000 {
        let alertSheet = UIActionSheet(title:nil, delegate: self as UIActionSheetDelegate, cancelButtonTitle:"取消", destructiveButtonTitle:nil, otherButtonTitles: "拍照", "从相册选择")
        alertSheet.show(in: self.view)
    }else{
        NewPushIMageViewcontroller(number:count)
    }
    print(count);
}

//MARK:提交
@objc func tap(_ btnCilck:UIButton) {
    mTableView.reloadData()
    perform(#selector(submitTheInterview), with:self, afterDelay:0.5)
}

@objc func submitTheInterview()  {
    let topView = self.view
    if ConnectingState().showConnect() {
        
        if arrayNumber.count < 1 {
            topView?.makeToast("至少选择一张图片", duration:3.0, position:CSToastPositionCenter)
            return;
        }
        if one.isEmpty || Two.isEmpty || arrayNumber.count < 1 {// || Three.isEmpty || String(number) == "0"
            topView?.makeToast("请填写完整信息,再进行提交", duration:3.0, position:CSToastPositionCenter)
        }else{
            topView?.showLoadingAnimationView()

            let dict:[String:String] = ["summary":one, "positionId":mID, "source":Three]
            Common.postJAVAImagsArr(arrayNumber as! [Any], andUrl:"kgc/app/saveInterviewQuestion", requestWithParm: dict as [AnyHashable : Any], success: { (resquestData, Any) in

                self.dismiss(animated: true, completion: {
                    self.Model(Type:"2",isSuccess:true)
                })

            }, failure: { (errorDict, Any) in

                self.dismiss(animated: true, completion: {
                    self.Model(Type:"1",isSuccess:false)
                })
            })
        }
    }else{
        topView?.makeToast("请检查网络...", duration:3.0, position:CSToastPositionCenter)
    }
}

func Model(Type:NSString,isSuccess:Bool) {
    let model = KGCDraftsModel()
    model.positionId = self.mID;
    model.gangweiname = self.Two
    model.imageArr = self.arrayNumber as! [Any]
    model.miaoshu = self.one
    model.laiyuan = self.Three
    model.numberType = Type as String?
    model.time = Common.getNowTimeTimestamp()
    if isSuccess == true
    {
        if self.typeString == "1" && self.pushAgainSucsessBlock != nil
        {
            self.pushAgainSucsessBlock!(cellndex)
        }
    }else
    {
       KGCDraftsModel().rowGetPath(model)
        
        if self.typeString == "1" && self.pushAgainSucsessBlock != nil
        {
            self.pushAgainSucsessBlock!("reload")
        }
    }
    let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
    NotificationCenter.default.post(name: notificationName, object: self,
                                    userInfo: ["value1":Type])
    self.view.hidenLoadingAnimationView()
    
    let picCount  = String(self.arrayNumber.count)
    let parmDic = ["actionName":"SubPiture","actionType":"9","idNumber":picCount] as [String : String]
    StudyAction.shared().add(parmDic)
}

//MARK:Cell回调代理
func method(tag: NSInteger, string: NSString){
    print(string)
    print(tag)
}

func assetPickerController(_ picker: ZYQAssetPickerController!, didFinishPickingAssets assets: [Any]!) {
    let  arrayTitle = assets! as NSArray
    if arrayTitle.count == 0 {
        
    }else{
        initViewAndButton()
         //imageArray  =  CY_PublicTool.changeAlalert(toData: assets as! [Any])! as NSArray
        imageArray  =  CY_PublicTool.changeAlalert(toData: assets as! [Any])! as NSArray
        arrayNumber = NSMutableArray.init(array: imageArray)

// for indexe in 0.. // let asset = arrayTitle[indexe] as! ALAsset
// let representation = asset.defaultRepresentation() //resulttll为ALAsset属性
//
// let imageBuffer = UnsafeMutablePointer.allocate(capacity: Int((representation?.size())!))
// print(representation?.size() as Any)
// let bufferSize = representation?.getBytes(imageBuffer, fromOffset: Int64(0),
// length: Int((representation?.size())!), error: nil)
// let data:NSData = NSData(bytesNoCopy:imageBuffer ,length:bufferSize!, freeWhenDone:true)
// arrayNumber.add(data)
// }
mTableView.reloadData()
}
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    
    let type:String = (info[UIImagePickerControllerMediaType]as!String)
    if type=="public.image"
    {
        picker.dismiss(animated:true, completion:nil)
        initViewAndButton()
        let img = info[UIImagePickerControllerOriginalImage]as?UIImage
        let wid = 3*SCREEN_WIDTH
        print(wid);
        let hig = (img?.size.height)!/((img?.size.width)!/wid)
        let size  = CGSize(width:CGFloat(wid), height:CGFloat(hig))
        let imagee = OriginImage(image:img!, size:size)
        let data:NSData = UIImageJPEGRepresentation(imagee, 1.0)! as NSData;
        arrayNumber.add(data)
        mTableView.reloadData()
    }
}

func initViewAndButton() {
    mBackView.removeFromSuperview()
    shareBtn.removeFromSuperview()
    mBackView = UIView()
    shareBtn = UIButton()
}

// MARK: UIActionSheetDelegate
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
    
    let buttonTitle = buttonIndex
    
    if actionSheet.tag == 101 {
        if buttonTitle == 0 {
            let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
            NotificationCenter.default.post(name: notificationName, object: self,
                                            userInfo: ["value1":"3"])
              self.dismiss(animated:true, completion: {})
        }else if (buttonTitle == 1){
            
        }
        return;
    }
    if buttonTitle == 0 {

    }else if (buttonTitle == 1){
        getImageFromPhotoLib()
    }else if (buttonTitle == 2){
        pressViewControoler()
    }
}

//MARK: 进行图片删除
func NewPushIMageViewcontroller(number:Int) {
    let imageEdit = imageEditController()
    imageEdit.delegate = self
    print(number);
    let strValue1 = String(number-1001)
    imageEdit.number = strValue1
    imageEdit.imagesArray = arrayNumber
    imageEdit.isByPresent = true
    self.present(imageEdit, animated: true) {};
}

func backUploadView(with imagesArray: NSMutableArray!) {
    initViewAndButton()
    print(imagesArray.count);
    arrayNumber = imagesArray
    mTableView.reloadData()
}

// MARK: 调用相机
func getImageFromPhotoLib()
{
    let imagePicker = UIImagePickerController()
    imagePicker.sourceType = .camera
    imagePicker.delegate = self 
    present(imagePicker, animated: true,  completion: {})
}

//MARK:- 全部获取图库文件夹
func pressViewControoler()
{
    let vc = ZYQAssetPickerController()
    vc.maximumNumberOfSelection = 9 - arrayNumber.count
    //MARK  单例使用的是9张图片
    KGCSingleton.getInstance().number = vc.maximumNumberOfSelection
    vc.assetsFilter = ALAssetsFilter.allAssets();
    vc.showEmptyGroups = true
    vc.delegate = self
    self.present(vc, animated: true){};
}

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

/*
// MARK: - Navigation

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

}
//请求接口
+(void)postJAVAImagsArr:(NSArray*)imageArr
andUrl:(NSString *)url
RequestWithParm:(NSDictionary *)params
success:(PostImageSuccessBlcok)success
failure:(PostImageFailureBlcok)failure{

NSMutableDictionary *newParams = [[NSMutableDictionary alloc]init];
NSString *baseUrl = [NSString stringWithFormat:@"%@/%@", [Common getBaseQuestionBankUrl], url];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *new =  [[NSMutableDictionary alloc] init];
[new setObject:params forKey:@"questionInterview"];
id paranms = [self jsonWithDictionary:new];
[newParams setObject:paranms forKey:@"json"];
[Common PrintLog:newParams BaseUrl:[NSString stringWithFormat:@"%@?", url]];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];

[manager POST:baseUrl parameters:newParams constructingBodyWithBlock:^(id formData)
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];

    for (int i = 0; i < imageArr.count; i++)
    {
         NSData *data = imageArr[i];
        NSLog(@"单张图片大小=  %lu kb", (unsigned long)data.length / 1000);
        NSString *name;
        if (i == 0){
            name = @"upDataAvatarFile";
        }else{
            name = [NSString stringWithFormat:@"upDataAvatarFile%d", i];
        }
        [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
    }
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(operation, responseObject);
        }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    if (failure){
        failure (operation, error);
    }
}];

}

你可能感兴趣的:(Swift上传图片,OC和Swift混编)