Search code examples
iosobjective-cswiftnsjsonserialization

Working in ObjC, not in swift. Whats wrong I am doing with JSON parsing in swift


I just wanted to Parse JSON from URL, The code below written in ObjC is working well and giving me correct response, but the code written in swift 3.1, not giving correct response. Giving me 500 Internal Error

Whats wrong I am doing. Can anyone guide. Thanks in advance.

I also tried to use converter from ObjC to Swift. But it fails with some errors, though I solve those errors, but still not giving correct output.

ObjC code below.

-(void)comparedatainserturl

{
    NSError *error;
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];

    [dict setObject:@"e639e129d0f3ab7d" forKey:@"imei_no"];
    [dict setObject:@"2017-08-29 12:18:44" forKey:@"current_time"];
    [dict setObject:@"0" forKey:@"tbl_offer_details"];
    [dict setObject:@"0" forKey:@"tbl_card_type"];
    [dict setObject:@"0" forKey:@"tbl_dashboard"];
    [dict setObject:@"0" forKey:@"tbl_category_details"];
    [dict setObject:@"0" forKey:@"tbl_sub_category_details"];
    [dict setObject:@"0" forKey:@"tbl_payment_option"];
    [dict setObject:@"0" forKey:@"tbl_payment_option_provider"];
    [dict setObject:@"0" forKey:@"tbl_like_favorite_share"];
    [dict setObject:@"0" forKey:@"tbl_user_details"];

    [arr addObject:dict];

    NSLog(@"arra :- %@",[arr description]);

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSString *string = [NSString stringWithFormat:@"data=%@",jsonString];

    NSLog(@"jsonData as string:\n%@", string);

    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

    NSString *urlString=[NSString stringWithFormat:@"%@",@"http://admin.scontos.com/index.php/Android_api/Offers_download"];

    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod: @"POST"];

    [request setHTTPBody: data];

    NSError *err;

    NSURLResponse *response;

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

    NSLog(@"gotresponsestring=%@", resSrt);
}

Swift Code below,

func  comparedatainserturl() {


        var arrayParams : NSDictionary = [:]

        arrayParams  = ["imei_no":"e639e129d0f3ab7d","current_time":"2017-08-2911:08:26","tbl_offer_details":"0","tbl_card_type":"0","tbl_dashboard":"0","tbl_category_details":"0","tbl_sub_category_details":"0","tbl_payment_option":"0","tbl_payment_option_provider":"0","tbl_like_favorite_share":"0","tbl_user_details":"0"]

        print(arrayParams)

        let valueArr : Array = [arrayParams]
        print(valueArr)

        let jsonData: Data? = try! JSONSerialization.data(withJSONObject: valueArr, options: .prettyPrinted)

        let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8)
        let string: String = "data=\(jsonString)"
        print("jsonData as string:\n\(string)")
        let dataa: Data? = string.data(using: String.Encoding.utf8)

        var _: NSError?
        let url1:URL = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
        let request:NSMutableURLRequest = NSMutableURLRequest(url: url1)
        request.httpMethod = "POST"

        request.httpBody = dataa

        var response: URLResponse?

        do{
            let urlData: Data? = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)


            let resstr = NSString(data: urlData!, encoding: String.Encoding.utf8.rawValue)
            print("Response is \(resstr! as String)")

        }catch{
            print(error)
        }

    }

Solution

  • In your swift code you are appending the following string.

    let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8) /In following line you are appending JsonString with optional value with optional key word with this "()". So you need to unwrap the optional value/

    let string: String = "data=\(jsonString!)"