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.
Related
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);
}
}
I want to send the city name to the server. I am getting latitude longitude using CLLocationManager. Then I use this link to do reverse geocoding.
https://maps.googleapis.com/maps/api/geocode/json?latlng=lati,longi&key=myApiKey
My problem is for different locations the number of address components are different. As an example, I am getting this array of address componeents for my current location.
"results": [
{
"address_components": [
{
"long_name": "ABC Rd",
"short_name": "ABC Rd",
"types": [
"route"
]
},
{
"long_name": "My City",
"short_name": "My City",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "My Province",
"short_name": "AB",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "My Country",
"short_name": "MC",
"types": [
"country",
"political"
]
}
],
For my client's location im getting this
results": [
{
"address_components": [
{
"long_name": "4",
"short_name": "4",
"types": [
"street_number"
]
},
{
"long_name": "some name",
"short_name": "some name",
"types": [
"route"
]
},
{
"long_name": "some name",
"short_name": "Some name",
"types": [
"political",
"sublocality",
"sublocality_level_2"
]
},
{
"long_name": "some name",
"short_name": "some name",
"types": [
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name": "city",
"short_name": "city",
"types": [
"locality",
"political"
]
},
{
"long_name": "some name",
"short_name": "Some name",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "Client country",
"short_name": "CC",
"types": [
"country",
"political"
]
},
{
"long_name": "12345",
"short_name": "12345",
"types": [
"postal_code"
]
}
],
How can I get the exact city name for different locations when the address components are different. First I tried to get it my component index number but since number of components are different I cant do that. Whats the correct way to do that? Please help me.
Thanks
UPDATE
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks objectAtIndex:0];
NSString *address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.subLocality,
placemark.subAdministrativeArea,
placemark.country];
// NSString *address=[self.placemark];
NSDictionary *dictAddress = [NSDictionary dictionaryWithDictionary:placemark.addressDictionary];
NSMutableDictionary *dictTxtData = [NSMutableDictionary dictionary];
NSLog(#"----LOCATION NAME----%#",[placemark.addressDictionary valueForKey:#"Name"]);
NSLog(#"-----STREET ADDRESS---%#",[placemark.addressDictionary valueForKey:#"Thoroughfare"]);
NSLog(#"-----CITY-----%#",[placemark.addressDictionary valueForKey:#"City"]);
strCountry=placemark.country;
NSLog(#"Address------%#",address);
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
Results I get
----LOCATION NAME----My Rd
-----STREET ADDRESS---My Rd
-----CITY-----(null)
Address------(null) My Rd
(null) (null)
(null)
My Country
This is how I call to location update
-(void)GetLocationData
{
if (self.locationManager == nil)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
}
else
{
nil;
}
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
else
{
nil;
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;//kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
The json responses from Google API can contain different place marks depending upon the location. Using index is not the correct approach. You can find the city name in json components where type is locality. Below is the code snippet
NSDictionary *locationData = [[json objectForKey:#"results"] objectAtIndex:0];
NSArray* addressComponents= [locationData objectForKey:#"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
for (NSDictionary* address in addressComponents)
{
NSArray* addressType = [address objectForKey:#"types"];
NSString* firstType = [addressType objectAtIndex:0];
if([firstType isEqualToString:#"locality"])
cityName = [address objectForKey:#"long_name"];
}
or you can also use CLGeocoder API in iOS.
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lat longitude:long];
[ceo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark %#",placemark.locality); // Get the city name
}];
call setLocation() in viewdidload method
func setLocation()
{
// self.view.backgroundColor = UIColor.whiteColor()
self.edgesForExtendedLayout = .None
// Set bounds to inner-west Sydney Australia.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
// print("dofo \(manager.location?.coordinate.latitude)")
// print(manager.location?.coordinate.longitude)
currentlat = (manager.location?.coordinate.latitude)!
cuurentlong = (manager.location?.coordinate.longitude)!
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentlat,
longitude: cuurentlong)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// Address dictionary
print(placeMark.addressDictionary)
// Location name
if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
print(locationName)
}
// Street address
if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
print(street)
}
// City
if let city = placeMark.addressDictionary!["City"] as? NSString {
print(city)
}
// Zip code
if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
print(zip)
}
// Country
if let country = placeMark.addressDictionary!["Country"] as? NSString {
print(country)
}
})
}
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);
}];
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"
},
I am searching a way to map 2 different arrays with the following JSON
"establishments": [
{
"id": 1,
"name": "Boudin Sourdough Bakery and Cafe",
"address": "1 Stockton St",
"zip_code": "94108",
"city": "San Francisco",
"country": "us",
"phone_number": "",
"position": {
"latitude": 37.78590500000001,
"longitude": -122.406289
},
"distance_from": 13.75783097391759
}
],
"places": [
{
"id": 3,
"name": "Private Place",
"position": {
"latitude": 37.78583400000001,
"longitude": -122.406417
},
"is_private": false,
"distance_from": 0
}
]
I have 2 different mappings. One for establishment and another for place. I found some help with the documentation but it's working only for PUT or POST requests.
Currently, I have the following request
[session.objectManager getObjectsAtPathForRouteNamed:APICallSearchSearchPlaceRouteName object:nil parameters:params success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSArray * resultPlaces=mappingResult.array;
[delegate APICallDidSearch:resultPlaces];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSError* myError=[self catchCustomErrorInRKError:error setDomain:#"Search"];
if (myError.code == NSURLErrorCancelled) return;
[delegate APICallDidFailSearch:myError];
}];
Mapping & Mapping Descriptor
RKEntityMapping *establishmentMapping = [APICallEstablishment RKGetEstablishmentMappingForManagedObjectStore:self.appDelegate.managedObjectStore];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:establishmentMapping
method:RKRequestMethodGET
pathPattern:APICallSearchSearchPlacePattern
keyPath:#"establishments"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[session.objectManager addResponseDescriptor:responseDescriptor];
I tried to adapt the example to my case with that (just before my request written above)
RKManagedObjectRequestOperation *operation = [session.objectManager appropriateObjectRequestOperationWithObject:establishmentMapping method:RKRequestMethodGET path:#"/whatever" parameters:nil];
operation.targetObject = nil;
//Does it still exist ? (XCode says an error)
//operation.targetObjectID = nil;
[session.objectManager enqueueObjectRequestOperation:operation];
Thank you in advance for your help.
Using session.objectManager getObjectsAtPathForRouteNamed... is a good option (better than trying to use RKManagedObjectRequestOperation directly).
You need to create another response descriptor, like responseDescriptor, but for places key path and mapping.