iphoneobjective-cnsurlconnectionnsurlrequest

Failed To Send JSON With NSUrlconnection


I am implementing this code which take apple in app purchase receipt from the current transaction (not listed here) I am converting it to base64 NSData object, create new NSString with the values and keys (json object) and send it through NSUrlconnection . when the compiler hits the init with request the app crashes after 2 seconds... without to get any response. this is the code.

    NSData *data = [NSData dataFromBase64String:receiptStr];
NSString *jsonString = [NSString stringWithFormat:@"{\"receipt-data\":\"(%@)\",\"password\":\"(%@)\"}", data, SHARED_SECRET];
NSLog(@"%@",jsonString);
savedReceipt = jsonString;
[[NSUserDefaults standardUserDefaults]setValue:savedReceipt forKey:@"savedrecipt"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSData *requestdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];    //urlData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSString stringWithFormat:@"%@",requestdata]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

Anyone have an idea what am I doing wrong? I am also new to JSON so it could be also a problem there.


Solution

  • That's because this line in your code:

    [request setHTTPBody:[NSString stringWithFormat:@"%@",requestdata]];
    

    Is trying to setHTTPBody to some formatted NSString, when the method is actually expecting NSData.

    Just use:

    [request setHTTPBody: requestdata];
    

    And see if you have better results.