Get a specific image from any URL like Facebook does - ios

My Question might be looks like similar to other questions but really this is not.(according to my knowledge). i can't understand that how to fetch a specific image from any URL Like Facebook does, i can't show you screen shot because i don't have real device. but i can show you Skype's screen shot taken from MAC. any help will be appreciated. thanks.
EDIT:i got favicon using this link but it is very small i want that in bigger size.

finally, i got the answer. this might be helpful to you thats why i post this answer.use this macro#define FACEBOOK_GRAPH #"https://graph.facebook.com/v2.3/oauth/access_token?client_id=USE_YOUR_CLIENT_ID&client_secret=USE_YOUR_CLIENT_SECRET&grant_type=client_credentials"NOTE: you can get "client_id" and "client_secret" by registering your Application on developer.facebook.com now make a call for FACEBOOK_GRAPH Like bellow.
AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer new];
AFHTTPRequestOperation* operation = [manager POST:FACEBOOK_GRAPH parameters:nil
success:^(AFHTTPRequestOperation* op, id responseObject){
//here pass your URL as a string and access Token as a string, access token will found in responseObject
}
failure:^(AFHTTPRequestOperation* op, NSError* error){
NSLog(#"\n\nerror--->%#\n\n",error.localizedDescription);
}];
[operation start];
now the second method to get image from our URL, use our URL and access Token got from above method
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
token = [token stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer new];
AFHTTPRequestOperation* operation = [manager POST:[NSString stringWithFormat:#"https://graph.facebook.com/v2.3/?id=%#&access_token=%#&scrape=true",url,token] parameters:nil success:^(AFHTTPRequestOperation* op, id responseObject){
NSLog(#"\n\nData Response==\n%#\n",responseObject);
//you will get Image URL in response
}failure:^(AFHTTPRequestOperation* op, NSError* error){
NSLog(#"##error--->\n%#",error.localizedDescription);
}];
[operation start];

Related

Wrong content-type(old header sent) being received by server side

I updated afnetwork to 2.0 due to 64 bit. I made a mistake at first using AFHTTPRequestSerializer, but the server side accept Json only. The wried thing was it works fine for me even I used AFHTTPRequestSerializer, so I didn't notice this problem and released the error app to public. Then I keep receiving user complain and somehow I rebuild my app on my device, and local server can catch my wrong content-type(application/x-www.form-urlencoded). After I updated the AFHTTPRequestSerializer to AFJSONRequestSerializer, it doesn't fix the problem, but the user still keep sending wrong content-type to server even they updated the app. New user has no problem, only happen on old user.
Is this related to cache problem?
Server Log:
10:22:53 AM] Mark 1 contentType is: application/x-www-form-urlencoded, method is: POST headers are: Connection=keep-alive&Content-Length=1880739&Content-Type=application%2fx-www-form-urlencoded&Accept=*%2f*&Accept-Encoding=gzip%2c+deflate&Accept-Language=en%3bq%3d1&Cookie=ASP.NET_SessionId%3dbby5dlk5afmsnqnoqpprvqpw&Host
10:04:56 AM] contentType is: application/json, method is: POST header is: Connection=keep-alive&Content-Length=40352 4&Content-Type=application%2fjson &Accept=*%2f*&Accept-Encoding=gzip%2c+deflate&Accept-Language=en%3bq%3d1&Cookie=ASP.NET_SessionId%3dcw3gdkg3sff1f0j50z2rnism&Host
my code is
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *operation = [manager POST:_url parameters:requestParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation success: %#\n %#", operation, responseObject);
NSDictionary *decoded = [self processResponce:responseObject failureBlock:failureBlock];
if (!decoded) return;
BOOL containsError = [self checkErrorStatus:decoded failureBlock:failureBlock];
if (containsError) return;
successBlock(decoded[#"Data"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failureBlock(FailureTypeUnknown, [error localizedDescription]);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
progressBlock(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
}];
as per your response, please set your manager's content type as below
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];

Sending a Request with JSON and Getting Back JSON iOS8

I have to send a JSON - with device id and type - to API, and it will give me another JSON with token and few other things.
I'm fairly new to iOS, it has been three weeks and I'm really new to web services. So, I couldn't figure out how to both send and get a JSON.
I'm trying to use AFNetworking at the same time, which is in my opinion the simplest way. So, I thought it might be good to use POST to send a JSON and I achieved with the following code:
NSString *uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];//DeviceID
NSLog(#"unique idf: %# and type: %#", uniqueIdentifier, [[NSNumber numberWithInt:1] stringValue]);
NSURL *baseURL = [NSURL URLWithString:BaseURLString];
NSDictionary *parameters = #{#"DeviceId" : uniqueIdentifier, #"Type" : [[NSNumber numberWithInt:1] stringValue]};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:BaseURLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
So, it returns me the device id and type, I know from writing to log. However I stuckted there. On the other hand, it doesn't reach to the success block. I debuged it right now, and also no printing on log screen although there was a command NSLog for it. What might be problem?
It's just confusing to construct a GET there, for me, honestly. So, I would be really appreciated if you can help me to figure out that situation.
Thanks.
Inside your success block do this -
[self performSelector:#selector(makeGetRequest:) withObject:responseObject];
Write the GET functionality in "makeGetRequest" method
-(void)makeGetRequest:(id)sender {
NSLog(#"responseObject - %#",sender);
// Write GET functionality here
}

How to use LinkedIn Share Api in iOS 7

I'm adding the ability to share an article on LinkedIn in an iOS 7 app using oauth2. I've gotten thru the authentication and have the access token. The documentation seems to be pretty clear about that, but it's odd, to actually post, things get pretty vague. I know I post here: http://api.linkedin.com/v1/people/~/shares appending the token.
But every example then just has the same code using OAMutableRequest, building the dictionary,etc. but they never explain what that is, how to incorporate that library or anything, its just strange. Is this the accepted best practice, the library hasn't been updated in 3 years so it has errors for arc and other things. All the code examples mention the same "consumer" property with no discussion of how or why that's needed. I can't seem to find how you build the post request with the parameters linkedin needs to post something on the site. Is OAMutableRequest the only way? If so, how have people updated it to work? Thanks so much!
After retrieve your Access Token you can use AFNetworking for a POST request like this example code:
NSString *stringRequest = #"https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=ACCESS_TOKEN&format=json";
//Request parameter on a dictionary (keys in camel case)
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc] initWithObjectsAndKeys: #"anyone",#"code",nil], #"visibility",
#"comment to share", #"comment",
[[NSDictionary alloc] initWithObjectsAndKeys:#"description share", #"description",
#"link_url", #"submittedUrl",
#"title share",#"title",
#"image_url",#"submittedImageUrl",nil],
#"content",nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
[manager POST:stringRequest parameters:update success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"result: %#", responseObject);
completionBlock(YES, responseObject, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError([error localizedDescription]);
completionBlock(NO, nil, error);
}];
Important: the keys of the dictionary are in camel case according to Linkedin API.
In the case linkedin give bad request (error 400), another way to create the dictionary is:
NSMutableDictionary *update = [[NSMutableDictionary alloc] init];
if(message)
{
//Set visibility
NSDictionary *visibility = [[NSDictionary alloc] initWithObjectsAndKeys:#"anyone", #"code", nil];
[update setObject:visibility forKey:#"visibility"];
//Set comment
[update setObject:message forKey:#"comment"];
//Set content or append imageUrl/postUrl to message to share
NSMutableDictionary *content = [[NSMutableDictionary alloc] init];
if(postUrl)
[content setObject:imageUrl forKey:#"submittedUrl"];
if(imageUrl)
[content setObject:imageUrl forKey:#"submittedImageUrl"];
if(postUrl || imageUrl)
[update setObject:content forKey:#"content"];
}
Andr3a88's answer might work, but I could never get everything figured out with linkedin's side. Luckily, they finally released a full sdk: https://developer.linkedin.com/docs/share-on-linkedin, https://developer.linkedin.com/docs/ios-sdk

AFNetworking 2 Response Error (Content type: text/html and not JSON)

After trying nearly every response on the subject, I've come up without a working answer to my problem.
The problem: So I've implemented the uploading portion of my app using AFNetworking 2.0.3 after porting from AFNetworking 1.3:
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock {
NSData* uploadFile = nil;
if ([params objectForKey:#"file"]) {
uploadFile = (NSData*)[params objectForKey:#"file"];
[params removeObjectForKey:#"file"];
}
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://54.204.17.38"]];
manager.responseSerializer = [AFJSONResponseSerializer serilizer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
AFHTTPRequestOperation *apiRequest = [manager POST:#"/API" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (uploadFile) {
[formData appendPartWithFileData:uploadFile name:#"file" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[apiRequest start];
}
The error I get when using this code is "Request failed: unacceptable content-type: text/html" I know you might be wondering if the server is responding with proper JSON, and I have every reason to think it is after inspecting the response headers in my browser that say 'MIME type: application/json'. Also, I am using 'header('Content-type: application/json')' at the top of my API as well (PHP API). Now, if I change the serialization type to 'AFHTTPResponseSerializer' instead of 'AFJSONResponseSerializer', it will not spit out the JSON error, but it will give me a different error (a random unrecognized selector error).
Any thoughts on why I cannot seem to get a JSON response out of this method?
You can set the AFHTTPSessionManager to accept any MIME Type:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
Got it! So, turns out, unknowingly, although my API was returning valid JSON, matter examining the header response logged on the Xcode side of things (thru NSLog(#"Error: %#", error);), it was actually returning text/HTML because it wasn't actually hitting the correct file, it was getting re-routed by a header somewhere. After explicitly stating the API path to be /API/index.php and not just /API, it started returning the valid JSON! Next, after making sure the response was properly JSON serialized (using requestManager.responseSerializer = [AFJSONResponseSerializer serializer];), the app worked!
Hopefully this helps someone who was having the same issue :)

AFNetworking 2.0 Request w. Custom Header

Ive tried to avoid asking such a newb question on here, but im a Android dev learning IOS and I cant figure out for the life of me how to add a simple header to my post requests using AFNetworking 2.0. Below is my code so far which works if i want to make a request that doesnt require a header.Could anyone show me via adding to my snippet or providing a alternate one that does this? I came across this tut: http://www.raywenderlich.com/30445 that shows how to add a header under the "A RESTful Class" heading , but its for afnetworking 1.0 and is now depreciated as far as i can tell.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"uid": #"1"};
AFHT
[manager POST:#"http://myface.com/api/profile/format/json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"JSON: %#", responseObject);
self.feedArray = [responseObject objectForKey:#"feed"];
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
} ];
}
Under AFHTTPRequestOperationManager you will notice a property called requestSerializer. This is of type AFHTTPRequestSerializer, and requests made through the HTTP manager are constructed with the headers specified by this object.
So, try this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"SomeValue" forHTTPHeaderField:#"SomeHeaderField"]
//Make your requests
You can read the headers dictionary from the request serializer as follows:
manager.requestSerializer.HTTPRequestHeaders
Note that once you set a header this way, it will be used for all other operations!
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"staging" password:#"dustylendpa"];

Resources