swift 中高德地图随时读取坐标地点的写法

自己写的方法  不比比  自己能看懂就行   只用作自己学习swift的总结



import UIKit


typealias block = (String,String) ->()


class MoveCarViewController: UIViewController,MAMapViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate,UITextFieldDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate {

    

    //大视图

    @IBOutlet weak var bgView: UIView!

    

    //小车按钮

    @IBOutlet weak var smallCarButton: UIButton!

    

    //大车按钮

    @IBOutlet weak var bigCarButton: UIButton!

    

    

    //车牌选择按钮

    @IBOutlet weak var plateButton: UIButton!

    

    //车牌号输入框

    

    @IBOutlet weak var plateTextFild: UITextField!

    

    //选择照片按钮

    @IBOutlet weak var photoButton: UIButton!

    

    //存放照片view

    @IBOutlet weak var ImageView: UIView!

    

    //存放照片button

    @IBOutlet weak var ImageButton: UIButton!

       

    //存放地图视图的地板

    

    @IBOutlet weak var firstView: UIView!

    

    

    //手动上报位置按钮

    @IBOutlet weak var manualButton: UIButton!

    

    //位置信息label


    @IBOutlet weak var locationLabel: UILabel!

    

    

    //提交按钮

    @IBOutlet weak var submitButton: UIButton!

    

    var popView : PopoverView?

    

    var db : FMDatabase?

    

    //车牌数据

    lazy var plates : [String] = {

        

        return PlateNumber.PlateNumbers() as! [String]

        

    }()

    

    var imageOne : UIButton?

    

    var imageTwo : UIButton?

    

    var index = 1

    

    var imageFileStr : String? = ""

    

    //对方车牌号

    var HPHM = UITextField()

    

    //挪车地址

    var Address = UILabel()

    

    //当前选中机动车类型

    

    var vehicleType1 = CarType()

    

    var vehicleType2 = CarType()

    

    var tmpcoordinate = CLLocationCoordinate2D()

    

    var carTypes : NSMutableArray!

    

    var carCitys : NSMutableArray!

    

    var tmpcity : String = ""

    

    var uploadFileList : NSMutableArray!

    

    var currentSelectedButton : UIButton = UIButton()

  

    var backImage : UIImageView!

    

    var label = UILabel()

    

    var city : String!

    

    var mapView : MAMapView?

    

    var search : AMapSearchAPI?

    

    var centerMarker : UIButton!

    

    var mapLacationManager = AMapLocationManager()

    

    var centerCoordinate:CLLocationCoordinate2D?

    

    //追踪指针位置的移动

    func mapView(mapView: MAMapView!, regionDidChangeAnimated animated: Bool) {

        

        delAddress()

        

    }

    

    var myBlock : block!

    



    

    

    

    

    //执行查询语句

    func searchCarType() {

        

                var resultSet : FMResultSet? = db?.executeQuery("SELECT rowid, * FROM chePaiType  ORDER BY rowid ASC;", withArgumentsInArray: nil)

        

                var tmparray : NSMutableArray = NSMutableArray.init(capacity: 2)

        

                //遍历结果

        

                while ((resultSet?.next()) != nil) {

        

                    var modle : CarType = CarType()

        

                    modle.rowid = Int(resultSet!.intForColumn("rowid"))

                    

                    modle.dm_code = String(resultSet!.intForColumn("dm_code"))

                    

                    modle.dm_name = String(resultSet!.intForColumn("dm_name"))

                    

                    modle.yx_biaoshi = String( resultSet!.intForColumn("yx_biaoshi"))

                    

                    

                    

        

                }

        

           self.carTypes = tmparray

    }

    

    //查询

    func searchCarCity() {

        

        //1.执行查询语句

        var resultSet : FMResultSet = (db?.executeQuery("SELECT rowid, * FROM chePaiCity;", withArgumentsInArray: nil))!

        

        //2.遍历结果

        

        var tmparray : NSMutableArray = NSMutableArray.init(capacity: 2)

        

        while resultSet.next() {

            

            var model : CarCity = CarCity()

            

            

            

            model.rowid = Int(resultSet.intForColumn("rowid"))

            

            model.city_name = String(resultSet.intForColumn("city_name"))

            

            model.cp_daihao = String(resultSet.intForColumn("cp_daihao"))

            

            

        }

        

        self.carCitys = tmparray

        

    }

    

    

    

    

    //查询当前默认城市的发证机关

    

    func searchCurCity(city: String) {

        

        var SQLStr : String = String.init(format: "SELECT rowid, * FROM chePaiCity WHERE city_name =\"%@\"", city)

        

        var resultSet : FMResultSet = (db?.executeQuery(SQLStr, withArgumentsInArray: nil))!

        

        while resultSet.next() {

            

            plateTextFild.text = resultSet.stringForColumn("cp_daihao") .stringByReplacingOccurrencesOfString(" ", withString: "")

            

        }

    }

    

    


    

    

    

    override func viewDidDisappear(animated: Bool) {

        

        super.viewDidDisappear(animated)

        

        self.mapView?.showsUserLocation = false

        

        self.mapView?.delegate = nil

        

        self.search!.delegate = nil

        

        

        

        

    }


    override func viewDidAppear(animated: Bool) {

        

        super.viewDidAppear(animated)

        

        self.mapView?.delegate = self

        

        self.search?.delegate = self

        

    }

    

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        self.view.backgroundColor = UIColor.whiteColor()

        

        

        

        title = "挪车服务"

        

        

        MAMapServices.sharedServices().apiKey = APIKey

        

        AMapSearchServices.sharedServices().apiKey = APIKey

        

        search = AMapSearchAPI()

        

        search?.delegate = self

        

        var uploadFileList : NSMutableArray = NSMutableArray.init(capacity: 2)

        

        

        initMapView()

        

        initBtns()



        

//        if ([self .respondsToSelector(automaticallyAdjustsScrollViewInsets)]) {

//            

//            self.automaticallyAdjustsScrollViewInsets = false

//        

//        }

//        

//        if ([self .respondsToSelector(setEdgesForExtendedLayout:)]) {

//            

//            self.edgesForExtendedLayout = UIRectEdge.None

//            

//            

//        }

        

        


        //历史

        var HistoryItem : UIBarButtonItem = UIBarButtonItem.init(title: "历史", style: UIBarButtonItemStyle.Done, target: self, action: "historyTapped")

        

        self.navigationItem.rightBarButtonItem = HistoryItem

        

        var path : String = NSConfig.filePath()

        

        var db : FMDatabase = FMDatabase(path : path)

        

        if db .open() {

            

            self.db = db

            

            

            db.close()

            

        } else {

            

            print("数据库打开成功")

            

        }

        

        self.tmpcity = ""

        

        

        

        makeUpButton()

        

        initView()

        

        getUserLocation()

        

    }


    

    //点击空白  收回键盘

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        

        view.endEditing(true)

    }

    

    //MARK: - 初始化控件

    

    private func setpUI() {

        

        

        

        

    }

    

    func initMapView() {

        

        mapView = MAMapView(frame: self.firstView.bounds)

        

        //是否显示用户位置

        mapView?.showsUserLocation = true

        

        //设定定位的最小更新距离

        mapView!.distanceFilter=16.0

        

        //追踪用户的location更新

        mapView?.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)

        

        //是否显示罗盘,默认为YES

        mapView?.showsCompass = true

        

        //是否显示比例尺,默认为YES

        mapView?.showsScale = true

        

        //地图比例尺级别

        mapView?.zoomLevel = 16

        

        //比例尺位置

        mapView?.scaleOrigin = CGPointMake(SCREEN_WIDTH * 0.00997, 0.0075)

        

        mapLacationManager = AMapLocationManager()

        

        mapView?.delegate = self

        

        mapLacationManager.requestLocationWithReGeocode(true) {

            

            (location, reGeocode, error) -> Void in

            

        }

        

        //设定定位精度

        mapView!.desiredAccuracy=kCLLocationAccuracyBestForNavigation

        

        mapView?.desiredAccuracy = kCLLocationAccuracyBest

        

        firstView!.addSubview(mapView!)

        

        

        

        

    }

    

    func initBtns() {

        

        //指针

        centerMarker = UIButton(frame: CGRectMake(0, 0, SCREEN_WIDTH * 0.0535, SCREEN_WIDTH * 0.5))

        

        centerMarker.center = (mapView?.center)!

        

        centerMarker.frame = CGRectMake(SCREEN_WIDTH * 0.45, SCREEN_HEIGHT * 0.2, SCREEN_WIDTH * 0.1090, SCREEN_WIDTH * 0.09)

        

        centerMarker.setImage(UIImage(named: "指针"), forState: .Normal)

        

        centerMarker.addTarget(self, action: "tappedOnee", forControlEvents: .TouchUpInside)

        

        mapView?.addSubview(centerMarker)

        

        

        //label

        

        label = UILabel(frame: CGRectMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.190 , SCREEN_WIDTH * 0.8, SCREEN_WIDTH * 0.02725))

        

        label.center = (mapView?.center)!

        

        label.text = "地址"

        

        label.textAlignment = NSTextAlignment.Center

        

        label.numberOfLines = 0

        

        label.layer.cornerRadius = 3.0

        

        label.layer.masksToBounds = true

        

        label.font = UIFont.systemFontOfSize(14.0)

        

        label.backgroundColor = UIColor.init(white: 0, alpha: 0.6)

        

        label.textColor = UIColor.whiteColor()

        

        

        //  self.view.addSubview(label)

        

        //文字大小自适应标签宽度

        label.adjustsFontSizeToFitWidth=true

        

        label.numberOfLines=2

        

        label.frame = CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.15 , SCREEN_WIDTH * 0.8, SCREEN_WIDTH * 0.109)

        

        

        // label.hidden = true

        

        mapView?.addSubview(label)

        

        

        

        

        

        //定位按钮

        var locationBtn: UIButton = UIButton(frame: CGRectMake(SCREEN_WIDTH * 0.0409, SCREEN_HEIGHT * 0.4, SCREEN_WIDTH * 0.1054, SCREEN_WIDTH * 0.1054))

        

        locationBtn.setImage(UIImage(named: "定位"), forState: .Normal)

        

        locationBtn.tag = 101

        

        locationBtn.addTarget(self, action: "btnSelector:", forControlEvents: .TouchUpInside)

        

        mapView?.addSubview(locationBtn)

        

        //刷新按钮

        var refreshBtn:UIButton = UIButton(frame: CGRectMake(SCREEN_WIDTH * 0.0409, SCREEN_HEIGHT * 0.35, SCREEN_WIDTH * 0.1054, SCREEN_WIDTH * 0.1054))

        

        refreshBtn.setImage(UIImage(named: "刷新"), forState: .Normal)

        

        refreshBtn.tag = 102

        

        refreshBtn.addTarget(self, action: "btnSelector:", forControlEvents: .TouchUpInside)

        

        mapView?.addSubview(refreshBtn)

        

        //缩小按钮

        var zoomOutBtn: UIButton = UIButton(frame: CGRectMake(SCREEN_WIDTH * 0.87, SCREEN_HEIGHT * 0.41, SCREEN_WIDTH * 0.085, SCREEN_WIDTH * 0.085))

        

        zoomOutBtn.setImage(UIImage(named: "缩小"), forState: .Normal)

        

        zoomOutBtn.tag = 103

        

        zoomOutBtn.addTarget(self, action: "btnSelector:", forControlEvents: .TouchUpInside)

        

        mapView?.addSubview(zoomOutBtn)

        

        //放大按钮

        var zoomInBtn : UIButton = UIButton(frame: CGRectMake(SCREEN_WIDTH * 0.87, SCREEN_HEIGHT * 0.37, SCREEN_WIDTH * 0.08, SCREEN_WIDTH * 0.08))

        

        zoomInBtn.tag = 104

        

        zoomInBtn.setImage(UIImage(named: "放大"), forState: .Normal)

        

        

        zoomInBtn.addTarget(self, action: "btnSelector:", forControlEvents: .TouchUpInside)

        

        mapView?.addSubview(zoomInBtn)

        

        

        

        

    }

    

    //按钮的实现方法

    func btnSelector(sender: UIButton) {

        

        switch sender.tag {

        case 101: //定位

            

            if centerCoordinate != nil {

                

                mapView?.setCenterCoordinate(centerCoordinate!, animated: true)

                

                

                

            }

            

        case 102: //刷新

            

           getLocationRoundFlag()

            

            mapView?.showsUserLocation = true //YES 为打开定位,NO 为关闭定位

            

        case 103: //缩小

            

            

            if mapView?.zoomLevel >= 4 && mapView?.zoomLevel <= 19 {

                

                mapView?.setZoomLevel((mapView?.zoomLevel)! - 1, animated: true)

                

            }else if mapView?.zoomLevel >= 3 && mapView?.zoomLevel < 4 {

                

                mapView?.setZoomLevel(3, animated: true)

            }

            

            

            

        case 104: //放大

            

            

            if mapView?.zoomLevel >= 3 && mapView?.zoomLevel <= 18 {

                

                mapView?.setZoomLevel((mapView?.zoomLevel)! + 1, animated: true)

                

            } else if mapView?.zoomLevel > 18 && mapView?.zoomLevel <= 19 {

                

                mapView?.setZoomLevel(19, animated: true)

                

            }

            

            

        default:

            

            print("not know")

            

        }

        

    }

    

    func tappedOnee() {

        

    }

    

    

    func getLocationRoundFlag(){

        

    }

    

    

    func mapView(mapView: MAMapView!, didUpdateUserLocation userLocation: MAUserLocation!, updatingLocation: Bool) {

        

        if updatingLocation {

            

            centerCoordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude,userLocation.coordinate.longitude);

            

            

        }

    }

    

    

    //跟随态

    func startFollowing() {

        

        mapView?.showsUserLocation = true

        

        mapView?.userTrackingMode = MAUserTrackingMode.FollowWithHeading

        

    }

    

    

    func confirm() {

      

        

        self.myBlock = {(address:String,city : String) ->() in

            

            let c = address.stringByAppendingFormat(self.label.text!, self.city)

            print(c)

            

            var VC : MoveCarViewController?

            

            VC?.locationLabel.text = self.label.text

            

        }

        

       

        

        self.navigationController?.popViewControllerAnimated(true)

        

    }

    

    

    func delAddress() {

        

        var point = CGPoint()

        

        point = CGPointMake(10, 10)

        

        var center = (mapView?.convertPoint(point, toCoordinateFromView: self.mapView))!

        

        self.searchReGeocodeWithCoordinate(center)

        

        locationLabel.text = label.text

        

       


        

    }

    

    

    

    

    

    //逆地理编码

    

    func searchReGeocodeWithCoordinate(coordinate:CLLocationCoordinate2D!) {

        

        let rego : AMapReGeocodeSearchRequest = AMapReGeocodeSearchRequest()

        

        rego.location = AMapGeoPoint.locationWithLatitude(CGFloat(coordinate.latitude), longitude: CGFloat(coordinate.longitude))

        

        rego.requireExtension = true

        

        self.search!.AMapReGoecodeSearch(rego)

        

        

    }

    

    //MARK:- MAMapViewDelegate

    

    func mapView(mapView: MAMapView!, didLongPressedAtCoordinate coordinate: CLLocationCoordinate2D) {

        

        searchReGeocodeWithCoordinate(coordinate)

        

    }

    

    func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {

        

        if annotation.isKindOfClass(MAPointAnnotation) {

            

            let annotationIdentifier = "invertGeoIdentifier"

            

            var poiAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier) as? MAPinAnnotationView

            

            if poiAnnotationView == nil {

                

                poiAnnotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

                

            }

            

            poiAnnotationView!.pinColor = MAPinAnnotationColor.Green

            

            poiAnnotationView!.animatesDrop = true

            

            poiAnnotationView?.draggable = true

            

            poiAnnotationView!.canShowCallout = true

            

            return poiAnnotationView

            

        }

        

        return nil

        

    }

    

    

    //MARK:- AMapSearchDelegate

    

    

    func AMapSearchRequest(request: AnyObject!, didFailWithError error: NSError!) {

        

       

    }

    

    func onReGeocodeSearchDone(request: AMapReGeocodeSearchRequest, response: AMapReGeocodeSearchResponse) {

        

        if (response.regeocode != nil) {

            

            label.text = response.regeocode.formattedAddress

            

            let tddd : AMapAddressComponent = response.regeocode.addressComponent

            

            self.city = tddd.city

            

            self.mapView?.showsUserLocation = true

            

            

        }

    }

    

    

    //清楚数据

    func clearMapData() {

        

        clearMapView()

        

        clearSearch()

        

    }

    

    func clearMapView(){

        

        mapView!.showsUserLocation = false

        

        mapView!.delegate = nil

    }

    

    func clearSearch(){

        

        self.search!.delegate = nil

        

    }

    

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    

    

    

    

    //按钮实现方法

    

    func makeUpButton() {

        

        //小车按钮

        smallCarButton.addTarget(self, action: "tappedOne", forControlEvents: .TouchUpInside)

        

        smallCarButton.tag = 101

        

        //边框

        smallCarButton.layer.borderWidth = 1

        

        smallCarButton.layer.borderColor = UIColor.lightGrayColor().CGColor

        

        smallCarButton.layer.cornerRadius = 5

        

        smallCarButton.clipsToBounds = true

        

//        //字体颜色变化

//        

//        smallCarButton.setTitleColor(UIColor.greenColor(), forState: .Selected)

//        

//

//        

//           smallCarButton.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)

//        

//        

        

        

        //大车按钮

        bigCarButton.addTarget(self, action: "tappedTwo", forControlEvents: .TouchUpInside)

        

        bigCarButton.tag = 102

        

       //边框

        bigCarButton.layer.borderWidth = 1

        

        bigCarButton.layer.borderColor = UIColor.lightGrayColor().CGColor

        

        bigCarButton.layer.cornerRadius = 5

        

        bigCarButton.clipsToBounds = true

        

       // bigCarButton.setTitle("大车", forState: .Normal)

//        bigCarButton.setTitleColor(UIColor.greenColor(), forState: .Selected)

        

        

        //车牌选择按钮

        plateButton.addTarget(self, action: "tappedThree:", forControlEvents: .TouchUpInside)

        

        plateButton.setImage(UIImage(named: "home_img_down"), forState: .Normal)

        

        plateButton.tag = 103

        

        

        //选择照片按钮

        photoButton.addTarget(self, action: "tappedFour", forControlEvents: .TouchUpInside)

        

        photoButton.tag = 104

        

        //上报位置按钮

        //locationButton.addTarget(self, action: "tappedFive", forControlEvents: .TouchUpInside)

        

        //locationButton.tag = 105

        

        //locationButton.setImage(UIImage(named: "moveCar_position_one"), forState: .Normal)

        

        //手动上传位置

       // manualButton.addTarget(self, action: "tappedSix:", forControlEvents: .TouchUpInside)

        

       // manualButton.tag = 106

        

       // manualButton.setImage(UIImage(named: "moveCar_position_two"), forState: .Normal)

        

        //位置信息label

        locationLabel.layer.cornerRadius = 5

        

        locationLabel.clipsToBounds = true

        

        

        

        //提交按钮

        submitButton.addTarget(self, action: "tappedSeven", forControlEvents: .TouchUpInside)

        

        submitButton.tag = 107

        

        submitButton.layer.cornerRadius = 5

        

        submitButton.clipsToBounds = true

        

        //大底板的边框

        bgView.layer.borderWidth = 1

        

        bgView.layer.borderColor = UIColor.lightGrayColor().CGColor

        

        bgView.layer.cornerRadius = 5

        

        bgView.clipsToBounds = true

        

        //照片view

        ImageView.layer.cornerRadius = 5

        

        ImageView.clipsToBounds = true

        

        

        //存放照片按钮

        ImageButton.addTarget(self, action: "tappedEight", forControlEvents: .TouchUpInside)

        

        ImageButton.tag = 108

        

        

        //车牌照输入框实现

        plateTextFild.keyboardType = UIKeyboardType.ASCIICapable

        

        plateTextFild.layer.borderColor = UIColor.init(white: 0.800, alpha: 1.00).CGColor

        

        plateTextFild.addTarget(self, action: "tappedNine:", forControlEvents: UIControlEvents.EditingChanged)

        

        plateButton.tag = 109

        

    

    }

    

    

    

    

    

    func historyTapped() {

        

        var VC = HistoryViewController()

        

        self.navigationController?.pushViewController(VC, animated: true)

        

    }

    

    func tappedOne() {

        

        print("我是第一个")

        

        currentSelectedButton.selected = false

        

        currentSelectedButton = smallCarButton

        

        currentSelectedButton.selected = true

        

        currentSelectedButton.setTitleColor(RGBA(62, g: 151, b: 210, a: 1.0), forState: UIControlState.Selected)

        

    }

    

        

    

    func tappedTwo() {

        

        print("我是第二个")

        

        currentSelectedButton.selected = false

        

        currentSelectedButton = bigCarButton

        

        currentSelectedButton.selected = true

        

        currentSelectedButton.setTitleColor(RGBA(62, g: 151, b: 210, a: 1.0), forState: UIControlState.Selected)

        

        

    }

    


    func tappedThree(btn : PlateBtn) {

        

        print("我是第三个")

        

        if popView != nil && popView!.isShow {

            

            popView?.dismiss(true)

            

        } else {

            

            popView = PopoverView(point: CGPointMake(btn.x + 30, CGRectGetMaxX(btn.frame) + 80), titles: plates, images: nil)

            

            popView?.show()

            

            popView?.selectRowAtIndex = {(row : Int) in

                btn.setTitle(self.plates[row], forState: UIControlState.Normal)

                

            }


            

        }

        

    }

    


    

    

    

    func tappedFour() {

        

        print("我是第四个")

        

        

        let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "相机", "相册")

        

        actionSheet.showInView(view)

        

        

        

    }

    

    func tappedFive() {

        

        print("我是第五个")

        

    }

    

    func tappedSix(gestureRecognizer : UITapGestureRecognizer) {

        

        //view.endEditing(true)

        

        print("我是第六个")

        

        let VC = MoveCarMapViewController()

        

        VC.centerCoordinate = tmpcoordinate


        VC.myBlock = {(address:String,city : String) ->() in

            

            self.locationLabel.text = address.stringByAppendingFormat(VC.label.text!, VC.city)

            

            self.tmpcity = city

            

                  

        }

        

        

        

        print(self.locationLabel.text)

        

        print(VC.label.text)

        

        print(VC.myBlock)

        

        navigationController?.pushViewController(VC, animated: true)

        


        

    }

    

    

    

    

    func tappedSeven() {

        

        print("我是第七个")

        

        var model : CarCity = CarCity()

        

//        var modelOne : ShareModel = ShareModel()

//        

//        if (!modelOne.NetWorking) {

//            

//            NSHelper.showAlertTitle("网络不可用,请检查网络连接。", forView: self.view)

//            

//            return

//            

//        }

    

        if (NSString.isNullOrEmpty(locationLabel.text)) {

            

            NSHelper.showAlertTitle("", message: "暂无法定位,请检查网络。", cancel: "确定")

            

            return

            

        }

        

        if (NSString.isNullOrEmpty(plateTextFild.text)) {

            

            NSHelper.showAlertTitle("请查看对方车牌号码是否输入正确?", forView: self.view)

            

            return

            

        }

        

        if (self.uploadFileList.count < 1) {

            

            NSHelper.showAlertTitle("", message: "请至少上传一张图片", cancel: "确定")

            

            return

        }

        

        let alert : UIAlertView = UIAlertView.init(title: nil, message: "确认提交挪车", delegate: nil, cancelButtonTitle: "确定")

        

        alert.showAlertViewWithCompleteBlock { (buttonIndex : NSInteger) in

            

            if (buttonIndex == 1) {

                

                //提交车辆信息

                

                let model : LocationModel = LocationModel()

                

                var species : String = ""

                

                if self.currentSelectedButton.titleLabel?.text == "小车" {

                    

                    species = "02"

                    

                }else {

                    

                    species = "01"

                    

                }

                

                

                let s = (self.plateTextFild.text! as NSString).substringToIndex(2)

                

                let dic : [String : AnyObject] = Dictionary(dictionaryLiteral: ("address" , self.locationLabel.text!),("mobile" , model.mobile),("vehicleType" , species),("vehicleType1",species),("city" , self.tmpcity),("fzjg" ,self.plateTextFild.text!),("userId" , model.userID),("vehicleNum" , s.stringByAppendingString(self.HPHM.text!)))

                

                let httpStr : String = AFAppDotNetAPIBaseURLString.stringByAppendingString(cfg.moveVehicle())

                

                print(httpStr)

                

                let HttpURL = httpStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

                

                let imageName : String = (self.uploadFileList.firstObject)! as! String

                

                let imageData : NSData = NSData.init(contentsOfFile: NSHelper.readDocumentsWithFileName(imageName))!

               

                

                let tools = NetWorkTools.sharedNetWorkTools()

                

                let parmeters  = ["suth" :tools.toAuthJSONString(),"info" : tools.toJSONString(dic),"picName" : imageName]

                

                print(parmeters)

                

                

                let hud : MBProgressHUD = MBProgressHUD.init(view: self.view)

                

                self.view.addSubview(hud)

                

                hud.labelText = "挪车提醒发送中..."

                

                hud.show(true)

                

                //发起网络请求

                let manager : AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()

                

               // manager.responseSerializer = [AFHTTPRequestSerializer serializer]

                

               // manager.responseSerializer = [AFJSONResponseSerializer serlailzer]

                

                manager.responseSerializer.acceptableContentTypes = NSSet.init(object: "text/html") as Set<NSObject>

                

                let operation : AFHTTPRequestOperation? = manager.POST(HttpURL!, parameters: parmeters, constructingBodyWithBlock: { (formData :AFMultipartFormData) in

                    

                    formData.appendPartWithFileData(imageData, name: "picFile", fileName: imageName, mimeType: "image/png")

                    

                    }, success: { (operation : AFHTTPRequestOperation, responseObject : AnyObject) in

                        

                        hud.hide(true)

                        

                        if dic["errCode"]?.integerValue == 0 {

                            

                            NSHelper.showAlertTitle(nil, message: "短信已发送至车主,请耐心等待!", cancel: "确定")

                            

                            self.HPHM.text = ""

                            

                            let cache : String = NSHelper.getUploadFileBasePath()

                            

                           try! NSFileManager.defaultManager().removeItemAtPath(cache)

                            

                           self.uploadFileList.removeAllObjects()

                            


                            

                        }else {

                            

                            NSHelper.showAlertTitle(nil, message: dic["msg"] as? String, cancel: "确定")

                            

                        }

                        

                    }, failure: { (operation : AFHTTPRequestOperation, error : NSError) in

                        

                        hud.hide(true)

                        

                        NSHelper.showAlertTitle(nil, message: "服务器异常,请稍后再试。", cancel: "确定")

                        

                        

                })

                

                

                

            }

           

        }

        

        

    }

    

    

    func tappedEight() {

        

        print("我是第八个,用来存照片的")

        

        

    }

    

    

    func tappedNine(textField: UITextField) {

        

        textField.text = textField.text?.uppercaseString

        

        plateTextFild.delegate = self

        

        textField.delegate = self

        

        

        

        if (textField == plateTextFild) {

            

            if (textField.text?.characters.count > 5) {

                

                textField.text = textField.text?.substringToIndex((textField.text?.startIndex.advancedBy(5))!)

                

                

            }

            

        }

        

    }

    

    

//    func dataToJsonString(object : AnyObject) {

//        

//        var jsonString : String = ""

//        

//        var error : NSError?

//        

//        let jsonData =  NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted,error:nil)

//        

//        if (jsonData == "") {

//            

//            print(error)

//            

//        } else {

//            

//            jsonString = String.init(data: jsonData, encoding: NSUTF8StringEncoding)!

//            

//        }

//        

//        return

//    }

//    

    

    

    func initView() {

        

//        let tmpp : CarType = ((self.carTypes?.firstObject)! as? CarType)!

//        

//        

//        plateTextFild.text = tmpp.dm_name

//        

//        vehicleType1 = tmpp

//        

//        plateTextFild.rightViewMode = UITextFieldViewMode.Always

//        

//        plateTextFild.rightView = plateButton

        

        

        //对方车牌号

        HPHM.borderStyle = UITextBorderStyle.RoundedRect

        

        HPHM.autocapitalizationType = UITextAutocapitalizationType.AllCharacters

        

        HPHM.keyboardType = UIKeyboardType.ASCIICapable

        

        HPHM.addTarget(self, action: "textFiledEditChanged:", forControlEvents: UIControlEvents.EditingChanged)

        

    }

    

    

    func getUserLocation() {

        

        self.mapView?.showsUserLocation = true

        

        if (self.mapView?.userTrackingMode != MAUserTrackingMode.Follow) {

            

            self.mapView?.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)

            

        }

        

    }

    

//    //设备更新后调用此接口

//    func mapView(mapView: MAMapView!, didUpdateUserLocation userLocation: MAUserLocation!, updatingLocation: Bool) {

//        

//        if (updatingLocation) {

//            

//            //取出当前位置的坐标

//            print(userLocation.title)

//            

//            self.searchReGeocodeWithCoordinate(userLocation.coordinate)

//            

//            print(userLocation.coordinate.longitude)

//            

//        }

//        

//        

//    }

//    

//    //逆地理编码

//    func searchReGeocodeWithCoordinate(coordinate:CLLocationCoordinate2D!) {

//    

//        let rego : AMapReGeocodeSearchRequest = AMapReGeocodeSearchRequest()

//        

//        rego.location = AMapGeoPoint.locationWithLatitude(CGFloat(coordinate.latitude), longitude: CGFloat(coordinate.longitude))

//        

//        rego.requireExtension = true

//        

//        self.search!.AMapReGoecodeSearch(rego)

//    

//    

//    }

//    

//    //逆地理编码回调

//    func onReGeocodeSearchDone(request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {

//        

//        if (response.regeocode != nil) {

//            

//           // var tmp : AMapPOI = response.regeocode.pois .first

//            

//            var tddd : AMapAddressComponent = response.regeocode.addressComponent

//            

//            self.tmpcity = tddd.city

//            

//            self.mapView?.showsUserLocation = false

//            

//        }

//        

//        

//        

//    }

    

    //定位失败时调用

    

    func mapView(mapView: MAMapView!, didFailToLocateUserWithError error: NSError!) {

        

        let status : CLAuthorizationStatus = CLLocationManager.authorizationStatus()

        

        if (CLLocationManager.authorizationStatus() == .Denied || CLLocationManager.authorizationStatus() == .Restricted) {

            

            var alret : UIAlertView = UIAlertView.init(title: "", message: "请开启定位功能,才能更好的为您服务", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "设置", "")

            alret.tag = 201

            

            alret.show()

            

        }

        

        

        

    }

    

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {

        

        if (alertView.tag == 201) {

            

            if (buttonIndex == 1) {

                

                //UIApplication.sharedApplication().openURL(NSURL(string: link)!)

                

                if #available(iOS 8.0, *) {

                    UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)

                } else {

                    

                    print("定位关闭,不可用")

                    

                }

                

            }

            

        }

        

        

    }

    

    

    

    

       


    /*

    // 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.

    }

    */


}



extension MoveCarViewController:UIActionSheetDelegate {

    

    func actionSheet(actionSheet:UIActionSheet,clickedButtonAtIndex buttonIndex: Int) {

        

        let picker = UIImagePickerController()

        

        picker.delegate = self

        

        if buttonIndex == 0 {

            

            return

            

        }else if buttonIndex == 1 {

            

            picker.sourceType = .Camera

            

        }else {

            

            picker.sourceType = .PhotoLibrary

            

        }

        

        presentViewController(picker, animated: true) { () -> Void in

            

            UIApplication.sharedApplication().statusBarStyle = .Default

            

        }

        

    }

    

}





extension MoveCarViewController :UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        

        UIApplication.sharedApplication().statusBarStyle=UIStatusBarStyle.LightContent

        

        self.dismissViewControllerAnimated(true, completion: nil)

        

        //存储照片

        var headImage : UIImage?

        

        headImage = info[UIImagePickerControllerOriginalImage] as? UIImage

        

        headImage = MyImageHandle.imageWithImageSimple(headImage, scaledToSize: CGSizeMake(120, 120))

        

        let nameStr : String = Guid.share().getGuid()

        

        saveImage(headImage!, name: "\(nameStr).png")

        

        imageFileStr = "\(AppSetting.PicturePath)\(nameStr).png"

        

        print(imageFileStr)

        

        

            

            //ImageButton.setImage(UIImage(contentsOfFile: imageFileStr!), forState: .Normal)

        

        ImageButton.setBackgroundImage(UIImage(contentsOfFile:imageFileStr!), forState: .Normal)

        

    }

    func saveImage(image:UIImage,name:String){

        

        let KCompressionQuality : CGFloat = 1

        

        let imageData : NSData = UIImageJPEGRepresentation(image,KCompressionQuality)!

        

        

        if NSFileManager.defaultManager().fileExistsAtPath(AppSetting.PicturePath) == false{

            

            try! NSFileManager.defaultManager().createDirectoryAtPath(AppSetting.PicturePath, withIntermediateDirectories: true, attributes: nil)

            

        }

        

        let sss : Bool = imageData.writeToFile("\(AppSetting.PicturePath)\(name)", atomically: false)

        

        print(sss)

        

        

    }

    

}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swift读取JSON数据可以使用NSJSONSerialization类。您可以使用以下代码示例来读取JSON数据: ```swift // 从一个本地项目资源读取data.json文件 if let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") { if let nsUrl = NSURL(fileURLWithPath: path) { if let nsData = NSData(contentsOfURL: nsUrl) { // 读取JSON数据 if let json = try? NSJSONSerialization.JSONObjectWithData(nsData, options: []) { // 读取普通数据 if let id = json["id"] as? String { print(id) } // 读取数组类型数据 if let array = json["data"] as? [String { print(array.count) } } } } } ``` 以上代码将从本地项目资源读取一个名为data.json的文件,并解析其的JSON数据。您可以通过键来访问JSON的数据,并将其转换为适当的类型。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [在Swift使用JSON](https://blog.csdn.net/cunjie3951/article/details/106922527)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Swift 读取,处理Json数据](https://blog.csdn.net/Riven_wn/article/details/51744646)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值