Decode URL into JSON - iphone

I am getting the following response
param=%7B%22paymentMode%22:%22%22,%22transactionId%22:%2231674%22,%22pgRespCode%22:%223%22,%22TxMsg%22:%22Canceled%20by%20user%22,%22authIdCode%22:%22%22,%22currency%22:%22INR%22,%22amount%22:%221.00%22,%22addressStreet1%22:%22Sesame%20street%22,%22addressStreet2%22:%22%22,%22isCOD%22:%22%22,%22loadStatus%22:%22fail%22,%22TxId%22:%22123456%22,%22addressCountry%22:%22India%22,%22firstName%22:%22Ankur%22,%22TxGateway%22:%22%22,%22signature%22:%2245558eb93513aa7a4f2fba24e0ba577b26eb5f40%22,%22addressState%22:%22Pune%22,%22lastName%22:%22Arya%22,%22addressCity%22:%22%22,%22TxRefNo%22:%22CTX1307151506338704178%22,%22loadAmount%22:%221.00%20INR%22,%22pgTxnNo%22:%22CTX1307151506338704178%22,%22TxStatus%22:%22CANCELED%22,%22email%22:%22daredevil.suyash#gmail.com%22,%22issuerRefNo%22:%22%22,%22mobileNo%22:%229900414420%22,%22addressZip%22:%22411045%22%7D
how can I decode it into the following
param={"paymentMode":"","transactionId":"31674","pgRespCode":"3","TxMsg":"Canceled by user","authIdCode":"","currency":"INR","amount":"1.00","addressStreet1":"Sesame street","addressStreet2":"","isCOD":"","loadStatus":"fail","TxId":"123456","addressCountry":"India","firstName":"Ankur","TxGateway":"","signature":"45558eb93513aa7a4f2fba24e0ba577b26eb5f40","addressState":"Pune","lastName":"Arya","addressCity":"","TxRefNo":"CTX1307151506338704178","loadAmount":"1.00 INR","pgTxnNo":"CTX1307151506338704178","TxStatus":"CANCELED","email":"daredevil.suyash#gmail.com","issuerRefNo":"","mobileNo":"9900414420","addressZip":"411045"}

You can try this method stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy]
Taken from this question urldecode in objective-c
//
NSString *param=#"%7B%22paymentMode%22:%22%22,%22transactionId%22:%2231674%22,%22pgRespCode%22:%223%22,%22TxMsg%22:%22Canceled%20by%20user%22,%22authIdCode%22:%22%22,%22currency%22:%22INR%22,%22amount%22:%221.00%22,%22addressStreet1%22:%22Sesame%20street%22,%22addressStreet2%22:%22%22,%22isCOD%22:%22%22,%22loadStatus%22:%22fail%22,%22TxId%22:%22123456%22,%22addressCountry%22:%22India%22,%22firstName%22:%22Ankur%22,%22TxGateway%22:%22%22,%22signature%22:%2245558eb93513aa7a4f2fba24e0ba577b26eb5f40%22,%22addressState%22:%22Pune%22,%22lastName%22:%22Arya%22,%22addressCity%22:%22%22,%22TxRefNo%22:%22CTX1307151506338704178%22,%22loadAmount%22:%221.00%20INR%22,%22pgTxnNo%22:%22CTX1307151506338704178%22,%22TxStatus%22:%22CANCELED%22,%22email%22:%22daredevil.suyash#gmail.com%22,%22issuerRefNo%22:%22%22,%22mobileNo%22:%229900414420%22,%22addressZip%22:%22411045%22%7D";
NSString *newParam = [param stringByReplacingPercentEscapesUsingEncoding:NSStringEncodingConversionAllowLossy];
NSLog(#"%#",newParam);

Do string replacement stuff with that to get it into a more readable form.
string = [string stringByReplacingOccurrencesOfString: #"%%22" withString:#"\""];
string = [string stringByReplacingOccurrencesOfString: #"%%7B" withString:#"{"];
string = [string stringByReplacingOccurrencesOfString: #"%%7D" withString:#"}"];
And so on, until you get it into something you want.
You are basically replacing the unicode representation of the character into the actual readable character

Related

Swift 3, in Poloniex trade Api get - "error": Invalid command

My code:
func testApi() {
Alamofire.request("https://www.poloniex.com/tradingApi", withMethod: .post, parameters: ["command":"returnDepositAddresses","nonce":nonce()], encoding: .json, headers: ["Key":apiKey,"Sign":newSecret]).responseJSON() { (dataBack) in
print(dataBack)
}
}
func nonce() -> Int {
let date = "\(NSDate().timeIntervalSince1970)"
let UnixInt = Double(date)!
return Int(UnixInt)
}
And I get it:
SUCCESS: {
error = "Invalid command.";}
I can't find any info about poloniex api with Swift or Objective C...
So if somebody can help - I'll be very grateful
Here is an example of how to form your NSURLRequest for poloniex.com.
Imagine that your:
API Key = #"apikey"
Secret = #"secret"
nonce = #"1"
Starting with the simplest things:
NSMutableURLRequest *theURLRequest = [NSMutableURLRequest new];
theURLRequest.URL = [NSURL URLWithString:#"https://poloniex.com/tradingApi"];
theURLRequest.HTTPMethod = #"POST";
NSString *theBodyString = #"command=returnBalances&nonce=1";
theURLRequest.HTTPBody = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[theURLRequest setValue:#"apikey" forHTTPHeaderField:#"Key"];
And now the hardest bit...
As to me, Poloniex documentation wasn't very clear on what they want under the "Sign" header field value, but basically they want you to pass a string, which should be a result of HMAC SHA512 encryption algorithm applied to both theBodyString and Secret (which in our example is simply #"secret").
Here is the function which would return you the HMAC SHA512 NSData:
#import <CommonCrypto/CommonHMAC.h>
NSData * getHMACSHA512FromSecretKeyStringAndBodyString(NSString *theSecretKeyString, NSString *theBodyString)
{
const char *cSecret = [theSecretKeyString cStringUsingEncoding:NSUTF8StringEncoding];
const char *cBody = [theBodyString cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char cHMAC[CC_SHA512_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA512, cSecret, strlen(cSecret), cBody, strlen(cBody), cHMAC);
return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}
So, running:
NSData *theData = getHMACSHA512FromSecretKeyStringAndBodyString(#"secret", #"command=returnBalances&nonce=1");
NSString *theString = [NSString stringWithFormat:#"%#", theData];
Would give us almost what we wanted.
Our result is equal to:
<c288f881 a6808d0e 78827ec6 ca9d6b9c 34ec1667 07716303 0d6d7abb 2b225456 31176f52 8347ab0f d6671ec5 3aec1f7d 3b6de8b8 e3ccc23d e62fd594 52d70db5>
While what we actually want (as per http://www.freeformatter.com/hmac-generator.html) is:
c288f881a6808d0e78827ec6ca9d6b9c34ec1667077163030d6d7abb2b22545631176f528347ab0fd6671ec53aec1f7d3b6de8b8e3ccc23de62fd59452d70db5
So, basically, just remove the <, > and symbols from your string;
theString = [theString stringByReplacingOccurrencesOfString:#"<" withString:#""];
theString = [theString stringByReplacingOccurrencesOfString:#">" withString:#""];
theString = [theString stringByReplacingOccurrencesOfString:#" " withString:#""];
[theURLRequest setValue:theString forHTTPHeaderField:#"Sign"];
Your theURLRequest is now ready and should succeed getting the tradingApi of poloniex.com.
Actually it's neither Swift nor iOS issue.
It's because you are accessing Trading API methods, and they may require some more additional parameters (except of nonce) in your POST request:
Check this:
All calls to the trading API are sent via HTTP POST to
https://poloniex.com/tradingApi and must contain the following
headers:
Key - Your API key. Sign - The query's POST data signed by your key's
"secret" according to the HMAC-SHA512 method. Additionally, all
queries must include a "nonce" POST parameter. The nonce parameter is
an integer which must always be greater than the previous nonce used.
Thus:
All responses from the trading API are in JSON format. In the event of
an error, the response will always be of the following format:
{"error":""}
https://temp.poloniex.com/support/api/

Formatting an String

I have an output string in this format .
I need to format the string such that i can display the URL separately and my Content, the description separately. Is there any functions , so i can format them easily ?
The code :
NSLog(#"Description %#", string);
The OUTPUT String:
2013-07-28 11:13:59.083 RSSreader[4915:c07] Description
http://www.apple.com/pr/library/2013/07/23Apple-Reports-Third-Quarter-Results.html?sr=hotnews.rss
Apple today announced financial results for its fiscal 2013 third quarter ended
June 29, 2013. The Company posted quarterly revenue of $35.3 billion and quarterly
net profit of $6.9 billion, or $7.47 per diluted share.
Apple sold 31.2 million iPhones, which set a June quarter record.
You should extract URL from string, then display it in formatted way.
A simple way to extracting URL is regular expressions (RegEX).
After extracting URL you can replace it with nothing:
str = [str stringByReplacingOccurrencesOfString:extractedURL
withString:#""];
You can use this :
https://stackoverflow.com/a/9587987/305135
If description string separated by line break (\n), you can do this:
NSArray *items = [yourString componentsSeparatedByString:#"\n"];
Regex is a good idea.
But there is a default way of detecting URLs within a String in Objective C, NSDataDetector.
NSDataDetector internally uses Regex.
NSString *aString = #"YOUR STRING WITH URLs GOES HERE"
NSDataDetector *aDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *theMatches = [aDetector matchesInString:aString options:0 range:NSMakeRange(0, [aString length])];
for (int anIndex = 0; anIndex < [theMatches count]; anIndex++) {
// If needed, Save this URL for Future Use.
NSString *anURLString = [[[theMatches objectAtIndex:anIndex] URL] absoluteString];
// Replace the Url with Empty String
aTitle = [aTitle stringByReplacingOccurrencesOfString:anURLString withString:#""];
}

regular expression to match " but not \"

How can I construct a regular expression which matches an literal " but only if it is not preceded by the escape slash namely \
I have a NSMutableString str which prints the following on NSLog. The String is received from a server online.
"Hi, check out \"this book \". Its cool"
I want to change it such that it prints the following on NSLog.
Hi, check out "this book ". Its cool
I was originally using replaceOccurencesOfString ""\" with "". But then it will do the following:
Hi, check out \this book \. Its cool
So, I concluded I need the above regular expression to match only " but not \" and then replace only those double quotes.
thanks
mbh
[^\\]\"
[^m] means does not match m
Not sure how this might translate to whatever is supported in the iOS apis, but, if they support anchoring (which I think all regex engines should), you're describing something like
(^|[^\])"
That is, match :
either the beginning of the string ^ or any character that's not
\ followed by:
the " character
If you want to do any sort of replacement, you'll have to grab the first (and only) group in the regex (that is the parenthetically grouped part of the expression) and use it in the replacement. Often this value labeled as $1 or \1 or something like that in your replacement string.
If the regex engine is PCRE based, of course you could put the grouped expression in a lookbehind so you wouldn't need to capture and save the capture in the replacement.
Not sure about regex, a simpler solution is,
NSString *str = #"\"Hi, check out \\\"this book \\\". Its cool\"";
NSLog(#"string before modification = %#", str);
str = [str stringByReplacingOccurrencesOfString:#"\\\"" withString:#"#$%$#"];
str = [str stringByReplacingOccurrencesOfString:#"\"" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"#$%$#" withString:#"\\\""];//assuming that the chances of having '#$%$#' in your string is zero, or else use more complicated word
NSLog(#"string after modification = %#", str);
Output:
string before modification = "Hi, check out \"this book \". Its cool"
string after modification = Hi, check out \"this book \". Its cool
Regex: [^\"].*[^\"]. which gives, Hi, check out \"this book \". Its cool
It looks like it's a JSON string? Perhaps created using json_encode() in PHP on the server? You should use the proper JSON parser in iOS. Don't use regex as you will run into bugs.
// fetch the data, eg this might return "Hi, check out \"this book \". Its cool"
NSData *data = [NSData dataWithContentsOfURL:#"http://example.com/foobar/"];
// decode the JSON string
NSError *error;
NSString *responseString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// check if it worked or not
if (!responseString || ![responseString isKindOfClass:[NSString class]]) {
NSLog(#"failed to decode server response. error: %#", error);
return;
}
// print it out
NSLog(#"decoded response: %#", responseString);
The output will be:
Hi, check out "this book ". Its cool
Note: the JSON decoding API accepts an NSData object, not an NSString object. I'm assuming you also have a data object and are converting it to a string at some point... but if you're not, you can convert NSString to NSData using:
NSString *responseString = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
More details about JSON can be found at:
http://www.json.org
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

encrypted data return nil string

I am using Rijndael Encryption Algorithm when I am going to encrypt it, it encrypted in NSData. I want that encrypted NSdata into NSString. I tried to convert it into string but it return nil. Have anyone any solutions to get into string.
I am doing like this
NSString *passphrase = #"super-secret";
NSStringEncoding myEncoding = NSUTF8StringEncoding;
NSString *alphaPlain = #"This is a encryption test.";
NSData *alphaDataPlain = [alphaPlain dataUsingEncoding:myEncoding];
NSLog(#" SimpleText value : %#",alphaPlain);
NSData *alphaDataCypher = [alphaDataPlain AESEncryptWithPassphrase:passphrase];
NSString *alphaStringCypher = [[NSString alloc] initWithData:alphaDataCypher encoding:myEncoding];
NSLog(#" Encrypted value : %#",alphaStringCypher);
It returns nil value.
Thanks
The encrypted data is no longer a UTF8 string, it's just some sequence of bytes, so decoding it as UTF8 fails.
What do you want to do with the string? If it's just for logging/debugging purposes, you could use [myData description] to get a hex string (with some extra whitespace for better readability). If you need this to transfer the data in a context where you need a textual representation, converting it to Base64 would be a good idea, see this answer for an easy way to do that.

Convert response string possibly to utf16

Hello
I am getting a response string from server this string:Kav\u00e1la.
After a search on google this "\u00e1" is UTF16.
I am trying to convert it using this:
NSString *myJson = [responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF16StringEncoding];
but nothing. Its the same
"\u00e1" is the character "รก" (lowercase a-acute).