Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

How to check and update mySQL with swift?

I have some code that should check if some id's exist and update DB by adding new rows in multiple tables. However I can't get it to work and my code is definitely not optimal.

Could you please help me with getting it to work and show me the proper methods for doing this?

Here is my class that is used to check and update the DB:

class UpdatePlanDB{
    
    private var UserPlanCheckIsGood : Bool = false
    private var PlanCheckIsGood : Bool = false
    private var bothChecked : Int = 0
    
    func getNewPlanId(completionHandler: @escaping (Result<Int, Error>) -> Void){
        getLowestPlanId(){ result in
                var lowestPlanId : Int = 2
                switch(result){
                case .success(let res):
                    lowestPlanId = res
                case .failure(let err):
                    completionHandler(.failure(err))
                }
                if(lowestPlanId >= 2){
                    completionHandler(.success(lowestPlanId - 1))
                }else{
                    var highestPlanId : Int = 0
                    self.getHeighestPlanId(){ resultH in
                        switch(resultH){
                        case .success(let res):
                            highestPlanId = res
                        case .failure(let error):
                            completionHandler(.failure(error))
                        }
                        completionHandler(.success(highestPlanId + 1))
                    }
                }
            }
    }
    
    func getLowestPlanId(completionHandler: @escaping (Result<Int, Error>) -> Void){
        let request = NSMutableURLRequest(url: NSURL(string: URL_GET_GET_LOWEST_PLAN_ID)! as URL)
        request.httpMethod = "POST"
        
        //request.httpBody = postString.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil{
                print(error!)
                completionHandler(.failure(NetworkError.badURL))
                return
            }else if let data = data {
                if var jsonString = String(data: data, encoding: .utf8) {
                    jsonString = jsonString.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
                    completionHandler(.success(Int(jsonString)!))
                }
            }
        }

        task.resume()
    }
    
    func getHeighestPlanId(completionHandler: @escaping (Result<Int, Error>) -> Void){
        let request = NSMutableURLRequest(url: NSURL(string: URL_GET_GET_HIGHEST_PLAN_ID)! as URL)
        request.httpMethod = "POST"
        
        //request.httpBody = postString.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil{
                print(error!)
                completionHandler(.failure(NetworkError.badURL))
                return
            }else if let data = data {
                if var jsonString = String(data: data, encoding: .utf8) {
                    jsonString = jsonString.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
                    completionHandler(.success(Int(jsonString)!))
                }
            }
        }

        task.resume()
    }
    
    func checkIdDoesNotExist(planId: Int, tableName: String, completionHandler: @escaping (Result<Bool, Error>) -> Void){
        let request = NSMutableURLRequest(url: NSURL(string: URL_CHECK_PLAN_ID_EXISTS)! as URL)
        request.httpMethod = "POST"
        
        let postString = "planId=(planId)&tableName=(tableName)"
        
        request.httpBody = postString.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil{
                print(error!)
                completionHandler(.failure(NetworkError.badURL))
                return
            }else if let data = data {
                if let jsonString = String(data: data, encoding: .utf8) {
                    if(jsonString == "0 results"){
                        completionHandler(.success(true))
                       
                    }else{
                        completionHandler(.success(false))
                        
                    }
                }
            }
        }

        task.resume()
    }
    
    func addToUserPlans(planId: Int, completionHandler: @escaping (Result<Bool, Error>) -> Void){
        checkIdDoesNotExist(planId: planId, tableName: "UserPlans"){ result in
            switch(result){
            case .success(let res):
                self.UserPlanCheckIsGood = res
                self.bothChecked += 1
            case .failure(let err):
                print(err)
                self.UserPlanCheckIsGood = false
                self.bothChecked += 1
            }
        }
        
        checkIdDoesNotExist(planId: planId, tableName: "Plans"){ result in
            switch(result){
            case .success(let res):
                self.PlanCheckIsGood = res
                self.bothChecked += 1
            case .failure(let err):
                print(err)
                self.PlanCheckIsGood = false
                self.bothChecked += 1
            }
        }
        
        while(bothChecked != 2){
            print("waiting")
        }
        
        if(PlanCheckIsGood && UserPlanCheckIsGood){
            let request = NSMutableURLRequest(url: NSURL(string: URL_ADD_USER_PLANS)! as URL)
            request.httpMethod = "POST"
            let postString = "userId=(Auth.auth().currentUser?.uid ?? "None")&planId=(planId)"
            
            request.httpBody = postString.data(using: String.Encoding.utf8)
            
            let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
                if error != nil{
                    print(error!)
                    completionHandler(.failure(NetworkError.badURL))
                    return
                }else if let data = data {
                    if let jsonString = String(data: data, encoding: .utf8) {
                        if(jsonString == "true"){
                            completionHandler(.success(true))
                        }else{
                            completionHandler(.success(false))
                        }
                    }
                }
            }

            task.resume()
        }else{
            completionHandler(.failure(NetworkError.badURL))
        }
    }
    
    func addPlan(planId: Int, completionHandler: @escaping (Result<Bool, Error>) -> Void){
        if(PlanCheckIsGood && UserPlanCheckIsGood){
            let request = NSMutableURLRequest(url: NSURL(string: URL_ADD_PLAN)! as URL)
            request.httpMethod = "POST"
            let postString = "userId=(Auth.auth().currentUser?.uid ?? "None")&planId=(planId)"
            
            request.httpBody = postString.data(using: String.Encoding.utf8)
            
            let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
                if error != nil{
                    print(error!)
                    completionHandler(.failure(NetworkError.badURL))
                    return
                }else if let data = data {
                    if let jsonString = String(data: data, encoding: .utf8) {
                        if(jsonString == "true"){
                            completionHandler(.success(true))
                        }else{
                            completionHandler(.success(false))
                        }
                    }
                }
            }

            task.resume()
        }else{
            completionHandler(.failure(NetworkError.badURL))
        }
    }
    
    func addProgressRow(completionHandler: @escaping (Result<Int, Error>) -> Void){
        
    }
}

And this is how I call it:

let newUpdate = UpdatePlanDB()
newUpdate.getNewPlanId(){result in
    switch(result){
    case .success(let res):
        newUpdate.addPlan(planId: res){ result2 in
            switch(result2){
            case .success(let res2):
                print(String(describing: res2))
            case .failure(let err2):
                print(err2)
            }
        }
                                                    
        newUpdate.addToUserPlans(planId: res){ result2 in
            switch(result2){
            case .success(let res2):
                print(String(describing: res2))
            case .failure(let err2):
                print(err2)
            }
        }
    case .failure(let err):
        print(err , "---------------------------")
    }
}

The following functions work fine: getNewPlanId(), getLowestPlanId(), getHeighestPlanId() and checkIdDoesNotExist().

Where the code is run it should return "true" twice if it succeeded. Feel free to ask any questions.

question from:https://stackoverflow.com/questions/65903596/how-to-check-and-update-mysql-with-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...