Perform POST request in Swift

后端 未结 2 1271
轻奢々
轻奢々 2021-01-31 20:27

I am trying to do something like this:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@\"http://google.com\"]];

request         


        
相关标签:
2条回答
  • 2021-01-31 20:58

    Using Alamofire to send HTTP POST request

    let request = NSMutableURLRequest(URL: NSURL(string: "https://www.google.com")!)
    request.HTTPMethod = "POST"
    
    let body = "email=\(email)&access_token=\(token)"
    request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
    
    Alamofire.request(request).responseJSON { response in
    
            NSLog("response.request: \(response.request)")  // original URL request
            NSLog("esponse.response: \(response.response)") // URL response
    
            switch response.result {
            case .Success:
                NSLog("Validation Successful")
            case .Failure(let error):
                // Logout
                NSLog("\(error), \(String(data: response.data!, encoding: NSUTF8StringEncoding))")
                return
            }
    
            // Save sip account information to NSUserdefaults
            if let json = response.result.value as? [String: AnyObject]{
                // Do your stuff
            } 
    }
    
    0 讨论(0)
  • 2021-01-31 21:11

    stringByAddingPercentEscapesUsingEncoding returns a string instead of an NSData object. According to this answer, you need to use this to convert to an NSData instance:

    let data = (anySwiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    
    0 讨论(0)
提交回复
热议问题