WebAPI call in Swift and fatal error: dictionary literal contains duplicate keys

I have used both swift and Objective-C to call an API with its parameter, I did it successfully in Objective C but I have a problem in Swift to call the API with its parameter.

I used the same keys as " Password " in two parameters . it doesn't work in Swift, but it does work correctly in Objective C.

Please guide me and update my Swift code.

thank

Swift Code

var params: [String: String] = ["FirstName":name, "ContactNumber":contact, "Email":email, "password": password,"password":repassword,"Rd_UserType":type]


    var request = NSMutableURLRequest(URL: NSURL(string: "http://local.in/api/AccountApi")!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

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

      

Mistake

fatal error: dictionary literal contains duplicate keys

      

Target C code is working correctly.

Objective-C Code

        NSString *post =[[NSString alloc] initWithFormat:@"FirstName=%@&ContactNumber=%@&Email=%@&password=%@&password=%@&Rd_UserType=%@",Name.text,ContactNumber.text,EmailAddress.text,Password.text,ReTypePassword.text,type];


        NSLog(@"PostData: %@",post);

        NSURL *url=[NSURL URLWithString:@"http://local.in/api/AccountApi"];



        NSLog(@"%@",url);


        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %ld", (long)[response statusCode]);

        if ([response statusCode] >= 200 && [response statusCode] < 300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);
        }

      

+3


source to share


2 answers


Your Swift code is significantly different from Obj-C code. Swift equivalent to

NSString *post =[[NSString alloc] initWithFormat:@"FirstName=%@&ContactNumber=%@&Email=%@&password=%@&password=%@&Rd_UserType=%@",Name.text,ContactNumber.text,EmailAddress.text,Password.text,ReTypePassword.text,type];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

      

will be something like



let post = "FirstName=\(Name.text)&ContactNumber=\(ContactNumber.text)&..."
let postData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
let postLength = "\(postData.length)"

      

Instead, you create a JSON dictionary as post data. This fails because a dictionary cannot have two values ​​for the same key. Also JSON may not be what the server expects.

+3


source


I solved my problem and I used this code.

Thank.



    let post = String(format: "FirstName=%@&ContactNumber=%@&Email=%@&password=%@&password=%@&Rd_UserType=%@",name,contact,email,password,repassword,type)

    NSLog("PostData: %@",post);

    var url1:NSURL = NSURL(string: "http://local.in/api/AccountApi")!

    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);

        }

    }

      

+1


source







All Articles