0

I am new to Swift and don't know Objective C. I want to convert this function fully to Swift.

void post_req()

    {
        NSString *oper = @"99";
        NSString *key = @"22";
NSString *query = @"22";
NSString *event_id = @"2";
NSError * error = nil;

NSString *myRequestString = [[NSString alloc] initWithFormat:@"operation=%@&key=%@&payload=%@", oper, key, query, event_id];
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:@"numbers"]];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSError *e = nil;
NSData *jData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jData options: NSJSONReadingMutableContainers error: &e];

id<NSObject> value = JSON[@"response"];

NSLog(@"responseData: %@", JSON);
NSLog(@"payData: %@", value);
NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];

if ([content isEqualToString:responseString])
{
    NSLog(@"responseData: %@", content);
}   

This is what I have so far. It isn't running properly.

func post_req() {

    let oper = "99"
    let key = "22"
    let query = "22"
    let event_id = "10"
    var error : NSError?

    let urlString = "http://numbers"
    let url = NSURL(string: urlString)!
    let request = NSMutableURLRequest(URL: url)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var myRequestString = NSString(format: "operation=%@&key=%@&payload=%@", oper, key, query, event_id)
    var myRequestData = NSData(bytes: myRequestString.UTF8String, length: myRequestString.length)
    //request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"content-type")
    request.HTTPBody = myRequestData

    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

        var content = String(data: data!, encoding: NSUTF8StringEncoding)!

        var jData = content.dataUsingEncoding(NSUTF8StringEncoding)

        do {

            let JSON = try NSJSONSerialization.JSONObjectWithData(jData!, options: .MutableContainers)


            print("responseData: %@", JSON)

        } catch {
            print("error")
        }
        print("responseData: %@", content)

    })
    task.resume() 
}

I think the issues are occurring in at the end of the request, with the encoding but I just wanted to include all the details.

1 Answer 1

2

Why don't you use Alamofire. It handles the jSon by default. We need not care about it. Just integrate the library to your project. Heres the instructions to do so: github.com/Alamofire/Alamofire

use "import Alamofire" to import the library to your class. And then use the following code:

let parameters = ["oper": "99" ,"key" : "22" , "query" : "22" , "event_id" : "2" , "error" : "" ]

Alamofire.request(.POST, "http://yoururl.com", parameters: parameters)
 .responseString { response in
     print("Response String: \(response.result.value)")
 }
 .responseJSON { response in
     print("Response JSON: \(response.result.value)")
   //Handle the json response here
  if let parseJSON = response.result.value {

        }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but this doesn't work. It's returning the same error as my own request. This is the response: { status code: 500, headers { "Content-Type" = "text/html"; Date = "Wed, 30 Mar 2016 20:18:10 GMT"; Server = localhost; "Transfer-Encoding" = Identity; } })

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.