0

Hi i am new to IOS App developement. My code is

func sendRequest<T: Decodable>(api: String, parameters: [String: String]? = nil, outputBlock: @escaping (T) -> () ) {
   
    guard let url = URL(string: "http://xxyyzz.com/appRegister.php") else {return}
    
    print("hitting : -", url.absoluteString)
    
    var request = URLRequest(url: url)
    
    request.httpMethod = "POST"
    
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
    request.addValue("application/json", forHTTPHeaderField: "Accept")
  
    let newparam = ["name": "rr", "pass": "123456", "email": "rr@rr.com", "passConfirm":"123456"]
    
    let httpBody = try? JSONSerialization.data(withJSONObject: newparam)
    
    request.httpBody = httpBody
    
    if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
    
        print(str)
    
    }
    
    URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
    
        DispatchQueue.main.async {
        
            Indicator.shared.hideProgressView()
            
            if let err = error {
            
                print(err.localizedDescription)
                
                return
            
            }
            
            guard let data = data else {return}
            
            do {
            
                let obj = String(data: data, encoding: String.Encoding.utf8)
                
                print(obj ?? "oberrrrr")
            
            }
        
        }
        
        }.resume()

}

and console printed result as per code is below

hitting : - http://xxyyzz.com/appRegister.php {"email":"rr@rr.com","passConfirm":"123456","name":"rr","pass":"123456"}

{"error":"Please enter all fields."}

url and parameters works well on postman that means their is something missing in my code.

Community
  • 1
  • 1
Gopal krishan
  • 179
  • 2
  • 4
  • 4
    Please read [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/a/284237/2225619) and the guide about asking good questions: https://stackoverflow.com/help/how-to-ask and adjust your question to be more specific – Capricorn Jul 19 '18 at 08:39
  • In POSTMAN you can get a Swift Code. It might be not always "a good code", but it should work and help you find out what's the difference. Usually to compare both, print the request URL, HeadersFields and HTTPBody to check which one is different. – Larme Jul 19 '18 at 08:58
  • just tried using postman code and the code is outdated and when tried resolving errors. one data variable is used for httpBody which never define before. – Gopal krishan Jul 19 '18 at 09:31
  • Show what you're doing in postman. Also, if you've done the registration in Postman with the same credentials, maybe this is the standard error the server returns in case a new user wants to register using the same e-mail or user? – Starsky Jul 19 '18 at 09:37
  • I always use different credentials and if same entry used, sever gives proper error of already created user – Gopal krishan Jul 19 '18 at 09:55

1 Answers1

1

just to answer the problem if anyone else faces this. this code is fine but the problem was with php web-service as the backend developer was not accepting json values as parameter instead form data was need to send. So, two types of fix can be made here

  1. accept json at backend by adding :-

    $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true);

  2. send form data instead json

    func sendRequest<T: Decodable>(api: String, parameters: [String: Any]? = nil, outputBlock: @escaping (T) -> () ) {
    
    guard let url = URL(string: api) else {return}
    
    print("hitting : -", url.absoluteString)
    
    var request = URLRequest(url: url)  
    
    if let parameters = parameters {
    
        request.httpMethod = "POST"
    
        var postArr = [String]()
    
        for(key, value) in parameters
        {
            postArr.append(key + "=\(value)")
        }
    
        let postString = postArr.map { String($0) }.joined(separator: "&")
        request.httpBody = postString.data(using: .utf8)
    
        if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
            print(str)
        }
    
    }
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        DispatchQueue.main.async {
            Indicator.shared.hideProgressView()
            if let err = error {
                print(err.localizedDescription)
                return
            }
            guard let data = data else {return}
            do {
                let obj = try JSONDecoder().decode(T.self, from: data)
                outputBlock(obj)
            } catch let jsonErr {                    
                print(jsonErr)
            }
        }
        }.resume()
    

    }

Gopal krishan
  • 179
  • 2
  • 4