Sending an HTTP POST request on iOS

前端 未结 7 1079
梦谈多话
梦谈多话 2020-11-22 12:04

I\'m trying to send an HTTP Post with the iOS application that I\'m developing but the push never reaches the server although I do get a code 200 as response (from the urlco

7条回答
  •  礼貌的吻别
    2020-11-22 12:43

    Using Swift 3 or 4 you can access these http request for sever communication.

    // For POST data to request

     func postAction()  {
    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
    let parameters = ["id": 13, "name": "jack"] as [String : Any]
    //create the url with URL
    let url = URL(string: "www.requestURL.php")! //change the url
    //create the session object
    let session = URLSession.shared
    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            return
        }
        guard let data = data else {
            return
        }
        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume() }
    

    // For get the data from request

    func GetRequest()  {
        let urlString = URL(string: "http://www.requestURL.php") //change the url
    
        if let url = urlString {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print(error ?? "")
                } else {
                    if let responceData = data {
                        print(responceData) //JSONSerialization
                        do {
                            //create json object from data
                            if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
                                print(json)
                                // handle json...
                            }
                        } catch let error {
                            print(error.localizedDescription)
                        }
                    }
                }
            }
            task.resume()
        }
    }
    

    // For get the download content like image or video from request

    func downloadTask()  {
        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
        //Create URL to the source file you want to download
        let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = URLRequest(url:fileURL!)
    
        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }
    
                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }
    
            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
            }
        }
        task.resume()
    
    }
    

提交回复
热议问题