How to send POST parameters in Swift?

前端 未结 4 1384
花落未央
花落未央 2020-12-23 14:46

Here some code:

var URL: NSURL = NSURL(string: \"http://stackoverflow.com\")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMetho         


        
相关标签:
4条回答
  • 2020-12-23 14:46
    class func postMethod (params: [String : AnyObject], apikey: String, completion: @escaping (Any) -> Void, failure:@escaping (Error) -> Void)
    {
        if Utils().isConnectedToNetwork() == false
        {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
                Utils().HideLoader()
            })
            return
        }
    
        let strURL = Constants.BASE_URL + apikey
        let url = URL(string: strURL)
        print(params)
        print(strURL)
    
        var token = String()
    
        if((Constants.USERDEFAULTS .value(forKey: "token")) != nil){
    
            token = Constants.USERDEFAULTS.value(forKey: "token") as! String
        }
        else{
             token = ""
        }
    
        let headers = [
            "Authorization": "Bearer \(token)",
            "Accept": "application/json"
        ]
    
    
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 120
        manager.request(url!, method: .post, parameters: params, headers: headers)
            .responseJSON
            {
                response in
                switch (response.result)
                {
                case .success:
                    let jsonResponse = response.result.value as! NSDictionary
                    print(jsonResponse)
                    completion(jsonResponse)
                    Utils().HideLoader()
                case .failure(let error):
                    Utils().showAlert("Something went wrong")
                    Utils().HideLoader()
                    failure(error)
                    break
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-23 14:47
     var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"
    
        NSLog("PostData: %@",post);
    
        var url1:NSURL = NSURL(string: url)!
    
        var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
    
        var postLength:NSString = String( postData.length )
    
        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
    
    
        var reponseError: NSError?
        var response: NSURLResponse?
    
        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
    
        if ( urlData != nil ) {
            let res = response as NSHTTPURLResponse!;
    
            NSLog("Response code: %ld", res.statusCode);
    
            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
    
                NSLog("Response ==> %@", responseData);
    
                var error: NSError?
    
                let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
    
    
                let success:NSInteger = jsonData.valueForKey("error") as NSInteger
    
                //[jsonData[@"success"] integerValue];
    
                NSLog("Success: %ld", success);
    
                if(success == 0)
                {
                    NSLog("Login SUCCESS");
    
                    self.dataArr = jsonData.valueForKey("data") as NSMutableArray 
                    self.table.reloadData()
    
                } else {
    
                    NSLog("Login failed1");
                }
    
            } else {
    
                NSLog("Login failed2");
    
            }
        } else {
    
             NSLog("Login failed3");
        }
    

    This will help you definitely

    0 讨论(0)
  • 2020-12-23 14:59

    Update to Swift 4.2

    This code is based on pixel's answer, and is meant as an update for Swift 4.2

    let bodyData = "key1=value&key2=value&key3=value"
    request.httpBody = bodyData.data(using: .utf8)
    
    0 讨论(0)
  • 2020-12-23 15:13

    No different than in Objective-C, HTTPBody expects an NSData object:

    var bodyData = "key1=value&key2=value&key3=value"
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    

    You'll have to setup the values & keys yourself in the string.

    0 讨论(0)
提交回复
热议问题