0

How to send JSON data using POST method to server in SWIFT

For Objective C i use this

NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:validEmailTF.text forKey:@"email"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:@"r=%@",jsonInputString];

NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",forgetPasswordUrl]];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil)
{
    jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSLog(@"Values =======%@",jsonDict);
}

Convert this code in Swift language. enter image description here Thanks

0

2 Answers 2

3

You can try this, may be it will help you

let request = NSMutableURLRequest(URL: NSURL(string: "Your forgetPasswordUrl")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

let params = ["email":validEmailTF.text] as Dictionary<String, String>

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")})

task.resume()
Sign up to request clarification or add additional context in comments.

3 Comments

pass the keys in the Dictionary like this let params = ["key1":"val1","key2":"val2","key3":"val3"] as Dictionary<String, String>
What about one of it contains another array of Dict? Like : ["key1":"val1","key2":"val2","key3":["key11":"val11","key12":"val12","key13":"val13"]]
@iUser use Dictionary<String, Any>
0

Simply converted your code to swift without tuning your code.

Try this:

    var get: NSMutableDictionary = NSMutableDictionary()
    get["email"] = validEmailTF.text
    var jsonData: NSData = NSJSONSerialization.dataWithJSONObject(get, options: kNilOptions, error: nil)
    var jsonInputString: String = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
    var post: String = NSString(format: "r=%@",jsonInputString)

    var get: NSMutableDictionary = NSMutableDictionary()
    var url: NSURL = NSURL(string: "\(forgetPasswordUrl)")
    var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
    var postLength: String = "\(postData.length())"
    var request: NSMutableURLRequest = NSMutableURLRequest.requestWithURL(url, cachePolicy: NSURLRequestReloadIgnoringCacheData, timeoutInterval: 120.0)
    request.URL = url
    request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.HTTPBody = postData

    var error: NSError
    var response: NSURLResponse
    var responseData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
    if responseData != nil {
        jsonDict = NSJSONSerialization.JSONObjectWithData(responseData, options: kNilOptions, error: &error)
        print("Values =======\(jsonDict)")

5 Comments

i think you a re using it in object c class. Create a class with swift and try
No, I am using Swift class
It works for me. without any error. screenshot added
I also uploadedt the image
What can i do ?? @Rajatp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.