如何使用POST方法使用表单数据调用REST API?

时间:2016-12-28 12:21:58

标签: ios objective-c swift rest

如何在swift iOS中使用post方法使用表单数据调用Rest Api?

我希望Swift能够使用“Post”方法:

使用“发布”

来使用已形成的数据命中Rest Api
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

    NSString *encodedUrl = [[NSString stringWithFormat:@"%@%@", self.BaseUrl, strMethodName]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *serverUrl = [NSURL URLWithString:encodedUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    NSError *error = nil;


    NSMutableString *body = [NSMutableString string];

    for (NSString *key in requestDict) {

        NSString *val = [requestDict objectForKey:key];

        if ([body length]){

            [body appendString:@"&"];

        }

        [body appendFormat:@"%s=%s", [[key description] UTF8String], [[val description] UTF8String]];

    }

   NSMutableData *postData = (NSMutableData *)[body dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    //    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];

4 个答案:

答案 0 :(得分:1)

func simplePostMethod()  {
        let url : URL = URL(string: "write your URL")!
        var request = URLRequest(url: url)
        let session = URLSession.shared
        request.httpMethod = "POST"
        // this is your input parameter dictionary
        let params = ["name":"Rizwan", "nickname":"Shaikh","password":"123456","gender":"male","dob":"1989-02-28","email":"hijk@gmail.com","device_id":"sffdg5645445","os":"ios"] as Dictionary<String, String>


        do{
            request.httpBody =  try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted)
        }
        catch
        {
            // catch any exception here
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let  task = session.dataTask(with: request, completionHandler: {(data,response,error) in


            if (data != nil)
            {
                do{
                    let dict =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves)
                    print(dict);
                }
                catch
                {
                    // catch any exception here
                }

            }

        }
        )

        task.resume()
    }

答案 1 :(得分:0)

尝试使用AFNetworking,非常易于使用。

检查一下:https://github.com/AFNetworking/AFNetworking

答案 2 :(得分:0)

        let body = { () -> Data! in
            do {
                if let fname = user.firstName, let lname = user.lastName, let email = user.email
                {
                    let params : [String : Any] = ["firstname" : fname, "lastname" : lname, "email":email]

                    return try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
                }


            } catch {
                print(error)
            }
            return nil
        }()
        var request = URLRequest(url: URL(string:url)!)
        request.httpMethod = "POST"
        request.httpBody = body!


        let session = URLSession.shared

        let dataTask = session.dataTask(with: request) {data,response,error in
            let httpResponse = response as? HTTPURLResponse

            if (error != nil) {
             print(error)
             } else {
             print(httpResponse)
             }

            DispatchQueue.main.async {
               //Update your UI here
            }

        }
        dataTask.resume()

答案 3 :(得分:0)

Swift 4.0

func ApiCall()
{
    let headers = [
        "authorization": authTokens,
        "content-type": "application/x-www-form-urlencoded",
        "cache-control": "no-cache",
        "postman-token": "-----------92fd-02d3-2742889ee66d"
    ]
    var userReg:Any?
    if let response = logindictionary["response"]as? NSDictionary{
        if let data = response["login"]as? NSDictionary
        {
            userReg = (data["userreg_id"])
            patientRegId = (data["patreg_id"])
        }}
    if patientRegId == nil{
        patientRegId = 0
    }
    let parameters = ["loc_user_id":locUserId,"userreg_id":userReg,"pat_reg_id":patientRegId!,"locId":locationId,"appuser_type":5] as [String : AnyObject]

    let namesData : NSData = NSKeyedArchiver.archivedData(withRootObject: parameters) as NSData
    do{
        let backToNames = try NSKeyedUnarchiver.unarchiveObject(with:namesData as Data) as! NSDictionary
    }catch{
        print("Unable to successfully convert NSData to NSDictionary")
    }
    let postData = NSMutableData(data: "loc_user_id=\(locUserId!)".data(using: String.Encoding.utf8)!)
    postData.append("&userreg_id=\(docregid!)".data(using: String.Encoding.utf8)!)
    postData.append("&pat_reg_id=\(patientRegId!)".data(using: String.Encoding.utf8)!)
    postData.append("&loc_id=\(locationId!)".data(using: String.Encoding.utf8)!)
    postData.append("&appuser_type=\(appUserType)".data(using: String.Encoding.utf8)!)

    let request = NSMutableURLRequest(url: NSURL(string: “—————URL——————“)! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)

    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as Data

    let session = URLSession.shared

    let dataTask = session.dataTask(with: request as URLRequest) { data,response,error in
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                print(jsonResult)
                if let resultData = jsonResult["response"]as? NSDictionary{
                    let doctorProfileDetails = resultData["doctor_profile"]as! NSDictionary
                   // print(doctorProfileDetails)
                if let valueAddrees = (doctorProfileDetails["address"] as? NSDictionary ){
                    let addressData = valueAddrees
                    print(addressData)
                        if let value = (addressData["address"] as? String){
                          addressLine1 = value
                        }else{
                            print("no key")
                        }
                        if let value = (addressData["buildng"] as? String){
                            buildng = value
                        }
                        if let value = (addressData["doorno"] as? String){
                            doorno = value
                        }
                        if let value = (addressData["land_mark"] as? String){
                            land_mark = value
                        }

                        if addressData["doorno"] as! String != " " && addressData["doorno"] as! String != "" {
                            doorno = doorno + ", "
                        }else{
                            doorno = ""
                        }
                        if addressData["buildng"] as! String != " " && addressData["buildng"] as! String != "" {
                            buildng = buildng + ", "
                        }else{
                            buildng = ""
                        }
                        if addressData["land_mark"] as! String != " " && addressData["land_mark"] as! String != ""{
                            land_mark = land_mark + ", "
                        }else{
                            land_mark = ""
                        }
                        DispatchQueue.main.async {
                            self.addressLabel.text = doorno + buildng + land_mark + addressLine1
                        }
                    }else{
                        DispatchQueue.main.async {
                            self.addressLabel.text = doctorProfileDetails["location_name"]as? String
                        }
                    }
                    locUserId = doctorProfileDetails["loc_user_id"]!
                    self.fvtdctr = doctorProfileDetails["favourate_docid"]as? Int
if doctorProfileDetails["rating"]as? Float != 0
                    {
                        DispatchQueue.main.async {
                            self.ratelabel.text = "\(doctorProfileDetails["rating"]as? Int ?? 0 )"
                        }
                    }
                    else
                    {
                        DispatchQueue.main.async {
                            self.ratingViews.isHidden = true
                        }
                    }
                    if doctorProfileDetails["years_of_exp"]as? Int != 0
                    {
                        DispatchQueue.main.async {
                            self.experience.text = "\(doctorProfileDetails["years_of_exp"]as? Int ?? 0) Years Experience"
                        }
                    }
                    else
                    {
                        DispatchQueue.main.async {
                            self.experianceView.isHidden = true
                        }
                    }
                    DispatchQueue.main.async {
                        if doctorProfileDetails["consult_fee"]as? Int == -2
                        {
                            feeDataValue = "Not available"
                            self.feeLabel.text = "Not available"
                        }
                        else if doctorProfileDetails["consult_fee"]as? Int == -1
                        {
                            feeDataValue = "Free"
                            self.feeLabel.text = "Free"
                        }
                        else if doctorProfileDetails["consult_fee"]as? Int == 0
                        {
                            feeDataValue = "Free"
                            self.feeLabel.text = "Free"
                        }
                        else
                        {
                            feeDataValue = "₹\(doctorProfileDetails["consult_fee"]as? Int ?? 0)"
                            feeFlotValue = (doctorProfileDetails["consult_fee"]as? Int)!
                            print(feeFlotValue)
                            self.feeLabel.text = "₹\(doctorProfileDetails["consult_fee"]as? Int ??  0) Consultation Fee"
                        }
                       //print(feeDataValue)
                    }
                    if doctorProfileDetails["consult_fee"]as? Int != 0
                    {

                    }
                    else
                    {
                        DispatchQueue.main.async {
                            self.feeLabel.text = "Fee Unavailable"
                        }
                    }
                    if doctorProfileDetails["recommendation"]as? Int != 0
                    {
                         DispatchQueue.main.async {
                        self.recommendLabel.text = "\(doctorProfileDetails["recommendation"] ?? 0)"
                        }
                    }
                    else
                    {
                        DispatchQueue.main.async {
                            self.recoendview.isHidden = true
                        }
                    }
                    if doctorProfileDetails["favourate_docid"]as? Int != 0
                    {
                        DispatchQueue.main.async {
                        self.fviteButton.isSelected = true
                        }
                    }else if doctorProfileDetails["favourate_docid"]as? Int == 0{
                        DispatchQueue.main.async {
                        self.fviteButton.isSelected = false
                        }
                    }

                    if let imageFile = (doctorProfileDetails["fileUrl"]as? String) {    // returns optional
                        self.backgroundimage.sd_setImage(with: URL(string:  imageFile), placeholderImage: UIImage(named: "ic_male"))
                        self.profileImage.sd_setImage(with: URL(string:  imageFile), placeholderImage: UIImage(named: "ic_male"))
                    }
                    else {
                          DispatchQueue.main.async {
                        self.backgroundimage.image = UIImage(named: "dzire-banner")
                        self.profileImage.image = UIImage(named: "ic_male")
                        }
                    }
                    if let reviewArray = doctorProfileDetails["review"]as?[NSDictionary]
                    {
                        //print(reviewArray)
                        self.attendeesArrayFromDatabase = reviewArray
                        if self.attendeesArrayFromDatabase.count != 0
                        {
                            self.secondVC.arrayReview = self.attendeesArrayFromDatabase
                             DispatchQueue.main.async {
                            self.secondVC.tableView.reloadData()
                                self.tableView.reloadData()
                            }
                        }
                    }
                    else{
                        DispatchQueue.main.async {
                            self.reviewLabelCell.isHidden = true
                            self.reviewCell.isHidden = true
                             self.cellHeight = 0
                        }
                    }
                        if let otherClinicData = doctorProfileDetails["clinics"]as?[NSDictionary]
                        {
                            //print(otherClinicData)

                            self.otherClinic.card = otherClinicData
                            //print(self.otherClinic.card)

                             DispatchQueue.main.async {
                             self.otherClinic.reloadData()
                            }
                        }
                        else{
                            DispatchQueue.main.async {
                                self.clinicsCell.isHidden = true
                                self.cellHeight = 0
                            }
                        //reviewCell.heightAnchor = 0
                    }
                    if let doctorUnit = doctorProfileDetails["doctor_names"]as?[NSDictionary]
                    {
                       // print(doctorUnit)

                        self.docUnitData.card = doctorUnit
                       // print(self.docUnitData.card)

                        DispatchQueue.main.async {
                            self.docUnitData.reloadData()
                        }
                    }
                    else{
                        DispatchQueue.main.async {
                            self.docUnitCell.isHidden = true
                            self.cellHeight = 0
                        }
                        //reviewCell.heightAnchor = 0
                    }
                    self.SessionArray = doctorProfileDetails["session"]as! [NSDictionary]
                    print(self.SessionArray)
                    self.docName = (doctorProfileDetails["doctor_name"]as? String)!
                    print(self.docName)
                    strLongValue = doctorProfileDetails["longitude"]as! Double
                    strLatValue = doctorProfileDetails["latitude"]as! Double

                    DispatchQueue.main.async {
                        print(doctorProfileDetails)
                        self.doctorNameLabel.text = doctorProfileDetails["doctor_name"]as? String
                        self.qualificationLabel.text = doctorProfileDetails["qualification"]as? String
                        //hospithalName.text = hospitalName
                        self.doctorNameDetailsLabel.text = doctorProfileDetails["location_name"]as? String
                       self.docUserReg = doctorProfileDetails["userreg_id"]
                        docregid = doctorProfileDetails["userreg_id"]
                        //                    self.feeLabel.text = "₹\(doctorProfileDetails["consult_fee"]as? Float ??  0) Consultation Fee"
                    }
                }
            }
        } catch let error {
            print(error.localizedDescription)
        }
    }

    dataTask.resume()
    self.tableView.reloadData()
  }