IOS JSON parsing into an objectkey - ios

I'm trying to implement the "Checking Duplicate Username" first of all, I have to get my json which stored all the record of my users. and get the object which is the username. Then matching them with the text from the UItTextField. My problem is that I can see all my json but I can't seems to parse it correctly.
-(IBAction) ChkUsername: (id) sender {
NSDictionary * userdata = [NSDictionary new];
[DIOSUser userGet: userdata success: ^ (AFHTTPRequestOperation * operation, id response) {
NSLog(#"%#", response);
DIOSSession * session = [DIOSSession sharedSession];
[session setUser: [response objectForKey: #"user"]];
NSDictionary * uname = [
[session user] objectForKey: #"name"];
if ([self.txtUsernameRegister.text isEqualToString: uname]) {
// if([uname isEqual:self.txtUsernameRegister.text]){
NSLog(#"You cannot use this Username");
} else {
NSLog(#"You can use this username");
}
}
failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {
NSLog(#"%#", [error localizedDescription]);
}];
}
I also got this error NSCFArray objectForKey:]
Edit here is how my JSON looks like.
{
uid: "60",
name: "pae1344",
mail: "viper1344#gmail.com",
theme: "",
signature: "",
signature_format: "plain_text",
created: "1396189622",
access: "0",
login: "1396189622",
status: "1",
timezone: "Asia/Bangkok",
language: "",
picture: "0",
init: "viper1344#gmail.com",
data: null,
uri: "http://localhost/drupal/rest/user/60"
},

Related

Disable loading images in WKWebView ios

I am creating an app, in which supremenewyork.com website is loaded in WKWebView. But when the website is loaded I do not want to load images in it. How can I do this in Objective-C.
I have following which prevent to load images of website in WKWebView. I have used content blocker rules which are documented official web site of Apple. Check here. Creating a Content Blocker.
- (void)viewDidLoad {
[super viewDidLoad];
// id blockRules = #" [{ \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"image\"] }, \"action\": { \"type\": \"block\" } }, { \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"style-sheet\"] }, \"action\": { \"type\": \"block\" } }, { \"trigger\": { \"url-filter\": \".*.jpeg\" }, \"action\": { \"type\": \"ignore-previous-rules\" } }] ";
id blockRules = #" [{ \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"image\"] }, \"action\": { \"type\": \"block\" } }] ";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.supremenewyork.com/"]];
[[WKContentRuleListStore defaultStore] compileContentRuleListForIdentifier: #"ContentBlockingRules" encodedContentRuleList:blockRules completionHandler:^(WKContentRuleList *contentRuleList, NSError *error) {
if (error != nil) {
NSLog(#"Error = %#", error.localizedDescription);
}
else {
WKWebViewConfiguration *configuration = self.webView.configuration;
[[configuration userContentController] addContentRuleList:contentRuleList];
dispatch_async(dispatch_get_main_queue(), ^{
[self.webView loadRequest:request];
});
}
}];
}
Output:
1.
Output:
2.
This is Swift version based on Mayur Karmur's answer:
let blockRules = "[{ \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"image\"] }, \"action\": { \"type\": \"block\" } }]";
WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "ContentBlockingRules", encodedContentRuleList: blockRules) {
contentRuleList, error in
if let error = error {
print("Error =", error.localizedDescription);
}else if let contentRuleList = contentRuleList{
let configuration = self.webView.configuration;
configuration.userContentController.add(contentRuleList);
}
}

httpResponse.data is Empty for IAP Receipt Validation with Parse CloudCode

I'm trying to validate an Apple IAP auto-renewing receipt (https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html), but the response payload seems to be (surprisingly) empty. I would greatly appreciate if you could point me in the right direction.
Here is the javascript implementation via Parse CloudCode:
Parse.Cloud.define('validateReceipt', function (request, response) {
// params:
// debugMode
// userObjectId
// receiptData
var storeURL = null;
if (request.params.debugMode) {
storeURL = 'https://sandbox.itunes.apple.com/verifyReceipt';
} else {
storeURL = 'http://buy.itunes.apple.com/verifyReceipt';
}
var receiptAsBase64EncodedString = request.params.receiptData;
var postData = {
method: 'POST',
url: storeURL,
headers: { 'Content-Type': 'application/json' },
body: { 'receipt-data': receiptAsBase64EncodedString,
'password': 'SHARED_SECRET' }
}
Parse.Cloud.httpRequest(postData).then(function (httpResponse) {
var expirationDate = httpResponse.data.latest_receipt.expiration_date;
var userQuery = new Parse.Query('_User');
userQuery.get(request.params.userObjectId, {
success: function(user) {
user.set('subscriptionExpirationDate', expirationDate);
user.save(null, {
success: function(thread) {
return response.success('Subscription Active');
},
error: function(user, error) {
console.error('Error saving subscriptionExpirationDate for User: ' + error.code + ' - ' + error.message);
return response.error('Error saving subscriptionExpirationDate for User: ' + error.code + ' - ' + error.message);
}
});
},
error: function(object, error) {
console.error('Error fetching User: ' + error.code + ' - ' + error.message);
return response.error('Error saving subscriptionExpirationDate for User: ' + error.code + ' - ' + error.message);
}
});
});
});
If I print httpResponse.data to the console, the output is:
No Message provided
However, if I implement the same logic from my client in obj-C, I have the expected result:
NSError *error;
NSDictionary *requestContents = #{
#"receipt-data": [receiptData base64EncodedStringWithOptions:0],
#"password": #"SHARED_SECRET"
};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
options:0
error:&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) {
NSError *error;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
}
}];
Printing jsonReponse:
{
environment = Sandbox;
"latest_receipt" = "...";
"latest_receipt_info" = (
{
"expires_date" = "2015-10-09 02:11:19 Etc/GMT";
[...]
},
status = 0;
}

Fetch authorized friends using graph library v2.4

I want to fetch Facebook user friends in my app using v2.4 graph library. I am getting count not names. I am not able to get authorized friends. Any help would be appreciable ?
// Function
-(void)fetchFriends
{
if ([FBSDKAccessToken currentAccessToken]) {
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/friends"
parameters:#{#"fields": #"id, name, first_name, last_name, picture.type(large), email"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"data : %#",result);
}];
}
}
// Response
data : {
data = (
);
summary = {
"total_count" = 3;
};
}
// Expected Response
{
"data": [
{
"name": "name",
"id": "id"
}
],
"paging": {
"Getting link here"
},
"summary": {
"total_count": 1
}
}
// Permissions
{
"data": [
{
"permission": "user_friends",
"status": "granted"
},
{
"permission": "public_profile",
"status": "granted"
}
]
}
It is working on Graph API Explorer but not in my app.

POST raw json code ios

i'm new to ios developing and i want to ask how can i post a raw json code to the server.
For Example: i want to send this JSON raw data to http://example.com/user
{
"user":
{
"username": "jkaaannyaad11",
"password": "secret123456",
"gender": "male",
"first_name": "assd",
"last_name": "ffsasd",
"birth_date": "can be null",
"phone_number": "12343234",
"have_car":"1",
"same_gender" :"0",
"uid": "this is id for facebook , can be null"
},
"home":
{
"longitude": "31.380301",
"latitude": "30.054272",
"name": "city"
},
"work":
{
"longitude": "30.068237",
"latitude": "31.024275",
"name": "village"
},
"email":
{
"email_type": "work",
"email": "hello.me#me.com"
}
}
so how can i do it ?
For Example in Android using the JSONObject i can easily oraganize them and then POST them to the website
JSONObject obj = new JSONObject();
JSONObject userObj = new JSONObject();
JSONObject homeObj = new JSONObject();
JSONObject workObj = new JSONObject();
JSONObject emailObj = new JSONObject();
try {
obj.put("user", userObj);
obj.put("home", homeObj);
obj.put("work", workObj);
obj.put("email", emailObj);
homeObj.put("longitude", homePlace.LocationRef.Lng);
homeObj.put("latitude", homePlace.LocationRef.Lat);
homeObj.put("name", homePlace.LocationRef.Address);
Use the AFNetworking library. On the repository page there are many examples including the one below to make a POST request.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

How to get NSArray from json

I have a JSON like this
{
accountList: [
{
acctId: "",
acctType: ""
},
{
acctId: "",
acctType: ""
}
],
tokenBack: "",
userId: "",
verificationCode: ""
}
and i want accountList array from that JSON as an array. Any one have solution?
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingMutableContainers error:nil];
NSArray *accountList = result[#"accountList"];

Resources