I need to get place_id from facebook for facebook checkin section.For that i am using following code.While requesting place id with access token sometines i get message as malformed access token,sometimes expired.
NSString *fbToken = [FBSession activeSession].accessTokenData.accessToken;
NSString *fbURL = [NSString stringWithFormat:#"https://graph.facebook.com/search?q=ritual&type=place¢er=9.952786,76.339828&distance=1000&access_token=%#",fbToken];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",fbURL, fbToken]];
NSLog(#"URL:%#",URL);
NSURLRequest *placeRequest = [NSURLRequest requestWithURL:URL];
//Send the request
[NSURLConnection sendAsynchronousRequest:placeRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (!connectionError) {
NSDictionary *Data = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"data = %#"Data);
}
}];
Related
I have tested on IAP of type Consumable with Sandbox environment. I want to make sure that the item I have bought is valid or not. but the result is always return with status "21004". I do nothing with share secret. So you can look the sample code that I follow apple when I succeed to purchase item:
- (void)verifyStatus:(SKPaymentTransaction *)transaction {
NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
NSError *receiptError;
BOOL isPresent = [[[NSBundle mainBundle] appStoreReceiptURL] checkResourceIsReachableAndReturnError:&receiptError];
if (!isPresent) {
NSLog(#"Validation failed");
}
NSString *receiptStr = [receiptData base64EncodedStringWithOptions:0];
NSDictionary *requestContents = #{#"receipt-data":receiptStr};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
options:0
error:nil];
if (!requestData) { /* ... Handle error ... */ }
NSURL *storeURL = [NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"];
NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
[storeRequest setHTTPMethod:#"POST"];
[storeRequest setHTTPBody:requestData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
/* ... Handle error ... */
} else {
NSError *error;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Respond : %#",jsonResponse);
if (!jsonResponse) { /* ... Handle error ...*/ }
/* ... Send a response back to the device ... */
}
}];
}
What's the problem I got? Please share your experience. Thanks
Please try following code and steps for SECRECT KEY.
#define SHARED_SECRET #"SECRECT KEY"
-(void)checkReceipt {
// verifies receipt with Apple
NSError *jsonError = nil;
NSString *receiptBase64 = [receiptData base64EncodedStringWithOptions:0];//receiptData NSData for validate Receipt
NSLog(#"Receipt Base64: %#",receiptBase64);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithObjectsAndKeys:
receiptBase64,#"receipt-data",
SHARED_SECRET,#"password",
nil]
options:NSJSONWritingPrettyPrinted
error:&jsonError
];
NSLog(#"%#",jsonData);
NSError * error=nil;
NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"%#",parsedData);
NSLog(#"JSON: %#",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
// URL for sandbox receipt validation; replace "sandbox" with "buy" in production or you will receive
// error codes 21006 or 21007
NSURL *requestURL = [NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:requestURL];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:jsonData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:req queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
/* ... Handle error ... */
} else {
NSError *error;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Respond : %#",jsonResponse);
if (!jsonResponse) { /* ... Handle error ...*/ }
/* ... Send a response back to the device ... */
}
}];
}
You need to change "SECRECT KEY" with the secret key that you get from iTunes Connect.sample look like 39fkjc38jd02mg72k9cn29dfkm39fk00.
Below is the step for create/view Secreate Key.
Login into iTunes Connect -> My Apps > Select your app > In-App
Purchases > View or generate a shared secret.
I am trying to get the number of twitter followers in my iOS App.
I find some Documentation regarding this issue:
https://dev.twitter.com/rest/reference/get/users/lookup
This is the code I have so far:
NSString *apiURLString = [NSString stringWithFormat:#"https://api.twitter.com/1.1/users/lookup.json?screen_name=%#", #"barackobama"];
NSURL *apiURL = [NSURL URLWithString:apiURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:apiURL];
request.HTTPMethod = #"GET";
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// ((NSHTTPURLResponse *)response).statusCode
NSLog(#"response = %#", response);
}];
However, I am pretty confused as how to send all the other parameters required for the request.
Thanks in advance!
I am using google places api to get that place's photo but i am unable to locate "photo_reference" field in the returned JSON. Here is what i have done so far.
NSString *urlString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/details/json?placeid=%#&key=%#",placeId,appKey];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSLog(#"Got Place Details");
NSDictionary *details = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *photo_reference = [[[[details valueForKey:#"result"] valueForKey:#"photos"] objectAtIndex:0] valueForKey:#"photo_reference"];
NSLog(#"");
NSString *urlString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/photo?maxwidth=302&maxheight=275&photoreference=%#&key=%#",photo_reference,appKey];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(#"Inner Request");
if (!connectionError) {
}];
}
}];
Places API documentation says that photo_reference could either be found from "Place Search" or "Place Details" requests. I got it from none.
I requested place details using place_id but the json doesnt have any "photos" key.
Same issue here
https://stackoverflow.com/questions/28317739/places-api-dont-retrieve-photos-on-detailed-petition-since-yesterday
Something change since yesterday but I don't know what or why.
EDIT: Today it's working again, maybe some random error from google.
I am working with GitHub's REST API for iOS and am having trouble getting it to work correctly with basic authentication. I have written the following code to view a users GitHub repositories:
NSString *requestString = [NSString stringWithFormat:#"https://%#:%##api.github.com/user/repos",userName,password];
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", strData);
}];
[dataTask resume];
I am getting the following response back:
{"message":"Requires authentication","documentation_url":"https://developer.github.com/v3"}
However when I do the following in my terminal:
curl -i GET https://userName:password#api.github.com/user/repos
I get the expected result back from GitHub. I'm not sure what authentication I am missing for my iOS app because I don't have anything in my curl statement that I don't have in my iOS code. Any help explaining what I'm missing is greatly appreciated.
It seems that something in NSURLSession doesn't like the username/password encoded in the URL (and to be honest, it isn't very secure as it can be exposed in proxy logs and is also prone to problems on the server side), so you have to encode the authorisation details into the HTTP headers.
This worked for me -
NSString *requestString = #"https://api.github.com/user/repos";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSData *userPasswordData = [[NSString stringWithFormat:#"%#:%#", userName, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authString = [NSString stringWithFormat:#"Basic %#", base64EncodedCredential];
NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders=#{#"Authorization":authString};
self.session=[NSURLSession sessionWithConfiguration:sessionConfig];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", strData);
}];
[dataTask resume];
I can see two possible reasons:
your password contains special characters that needs to be "percent escaped": see "NSString method to percent escape '&' for URL"
the ## is somehow misinterpreted: you can try to POST the username and password as in this question
I'm trying to get a JSon string but some words has "á, é, ç", etc.
The JSon is:
{"Error":"", "Result":{"Transacoes": [{"ClienteID":"1","ID":"915","Banco":"Bradesco","Fornecedor":"","Tipo":"Cartão de crédito - Bradesco Visa","ValorCredito":"0,0000","ValorDebito":"4000,0000","Vencimento":"","Pagamento":"03/08/2012 00:00:00","Descricao":"Cartão Bradesco Visa","Lançamento":"03/08/2012 15:18:12"},{"ClienteID":"1","ID":"916","Banco":"Bradesco","Fornecedor":"","Tipo":"Alinhamento da Conta Bancária","ValorCredito":"22398,9200","ValorDebito":"0,0000","Vencimento":"","Pagamento":"02/08/2012 00:00:00","Descricao":"FGTS","Lançamento":"07/08/2012 11:12:16"}]}}
And the code is:
-(void)viewWillAppear:(BOOL)animated {
NSString *urlAddress = [NSString stringWithFormat:#"http://SITE?action=transacoes&AuthToken=%#&DataDe=02/08/2012&DataAte=03/08/2012", self.usuario.authToken];
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest: request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#", JSON);
}
failure: ^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
NSLog(#"ERROR: %#", error);
}];
[operation start];
}
Your app throws Exception because it can't get data from server ,which you are requesting. SO first make sure it receives some data and then implement following code
Try Following code to parse your json data, i tried with my app, its working fine with that special symbols as well.
NSString *urlAddress = [NSString stringWithFormat:#"http://SITE?action=transacoes&AuthToken=%#&DataDe=02/08/2012&DataAte=03/08/2012", self.usuario.authToken];
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if([responseData bytes] > 0)
{
// It will work only IOS 5.0 or later version otherwise you can use any third party JSON parsers (eg. SBJSON)
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error];
NSLog(#"%#",[[[[json objectForKey:#"Result"] objectForKey:#"Transacoes"] objectAtIndex:1] valueForKey:#"Descricao"]);
NSLog(#"%#",[[[[json objectForKey:#"Result"] objectForKey:#"Transacoes"] objectAtIndex:1] valueForKey:#"Tipo"]);
}