Send the image on API using post method from imagepicker - iphone

I want to make a registration form, here I have taken all UITextField data in string and send on the api using post method but I don't know how to send image on api with all data?

Try Following code Snippet
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL: [NSURL URLWithString:#"Your URL"]];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"YourValue",#"ValueName",#"YourValue",#"ValueName", nil];
NSData *imageData = UIImagePNGRepresentation(img_Picture);
[manager POST:#"Your URL" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"logo" fileName:#"image.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#, %#", error, operation.responseString);
}];
Where parameters contains all your textfield's data.
And Logo is image parameter name which is used in api coding.

Related

how to get read permission before publishing permission for uploading video on Facebook using SLRequest?

I am simply trying to integrate Facebook sharing into my app, my app's end product is a video hence uploading and sharing the final compilation with friends is what i have in mind, I am using native social framework with ACAccount Framework, for my app to work there seems to be weird logic from Facebook that i need to ask for read permission before i ask for publish_stream permission and that they cant be immediately after(read somewhere), my question is where and how should i implement this logic in my code, heres my code
ACAccountStore* accountStore = [[ACAccountStore alloc] init];
NSDictionary *options = #{
ACFacebookAppIdKey: #"My app ID",
ACFacebookPermissionsKey: #[#"user_birthday"],
ACFacebookAudienceKey: ACFacebookAudienceOnlyMe
};
ACAccountType *facebookAccountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore
accountsWithAccountType:facebookAccountType];
ACAccount * facebookAccount = [accounts lastObject];
NSLog(#"access to facebook account ok %#", facebookAccount.username);
NSData *videoData = [NSData dataWithContentsOfFile:[_fURL absoluteString]];
NSLog(#"%#",[_fURL absoluteString]);
NSLog(#"video size = %d", [videoData length]);
NSDictionary *params = #{
#"title": #"Me being silly",
#"description": #"Me testing the video upload to Facebook with the new system."
};
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:requestURL
parameters:params];
[request addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[_fURL absoluteString]];
request.account = facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response,NSError * error){
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response = %#", responseString);
}];
Yes I am missing publish stream permission but i cant seem to figure out where should i put it, this whole code is under one method which is called when user presses a button
It is very simple. That is my implementation of it:
- (void)requestAccessToFacebookAccountWithCompletionHandler:(QCFacebookCommunicatorCompletionHandler)completionHandler {
[[self accountStore] requestAccessToAccountsWithType:[self accountType] options:[self facebookAccountAccessRequestOptionsForReadStreamPermission] completion:^(BOOL accessForReadingGranted, NSError *error) {
if (accessForReadingGranted) {
[[self accountStore] requestAccessToAccountsWithType:[self accountType] options:[self facebookAccountAccessRequestOptionsForPublishStreamPermission] completion:^(BOOL accessForWrittingGranted, NSError *error) {
if (accessForWrittingGranted) {
completionHandler(YES, nil);
} else {
completionHandler(NO, [error userInfo]);
}
}];
} else {
completionHandler(NO, [error userInfo]);
}
}];
}
I just use a helper methods to return dictionaries with options, other stuff is similar to yours.
Then, you can paste your code that is responsible for video uploading instead of the completionHandler calls, or you can use this implementation, and upload video only if the success == YES in completionHandler.
Hope it helps!

Iphone - AFNetworking Login Form always returns 404

I'm having troubles with AFNetworking, decided to use it since ASIHTTP is long deprecated, and I'm trying to use it in a login form request, but the response code is always -1011.
here is my code :
NSString *urltest = [NSString stringWithFormat:#"%#%#/", SERVER_ADDRESS, API_ADDRESS];
NSURL *url = [NSURL URLWithString:urltest];
NSLog(#"url address : %#",url);
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.allowsInvalidSSLCertificate = TRUE;
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
_email.text, #"email",
_password.text, #"password",
nil];
// Here I try doing my login request using AFHTTPRequestOperation
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"/auth/login" parameters:params];
[request setValue:#"application/x-www-form-urlencoded; charset=UTF8" forHTTPHeaderField:#"Content-Type"];
//Notice the different method here!
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", error);
}];
//Enqueue it instead of just starting it.
[httpClient enqueueHTTPRequestOperation:operation];
// Here I try doing my login request using the postPath:parameters: method
[httpClient postPath:#"/auth/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self performSegueWithIdentifier:#"AuthOK" sender:self];
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request failed with code %d for %# for request : %#",error.code , error.localizedDescription,httpClient.baseURL);
}];
And none of these two methods are working, I'm guessing I'm doing something wrong somewhere
btw, the server I login to, has an unsigned ssl certificate, but I handled the error by adding
#define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 1
in AFURLConnectionOperation.h
I use Charles to monitor http requests, and it gives me a "SSLHandshake: Remote host closed connection during handshake"
My app runs with iOS 5.
Anyone has insights on this?
Leo
Well my solution was to initialize my request with an empty url and then in the postPath, put the whole address.
You need to install Charles' SSL Certificate on your device to decrypt SSL traffic
http://www.charlesproxy.com/documentation/faqs/ssl-connections-from-within-iphone-applications/

How to autopost on twitter in iphone?

I want to auto post my static link in twitter using iphone application (without using dialog box, cancel option , send option). is it possible?
I Found this links for this:
Post in iOS 5 with TWRequest
Post in iOS 6+ with SLRequest
Use this method of Twitter Framework:
NSString *statusesShowEndpoint = #"https://api.twitter.com/1.1/statuses/update.json";
NSDictionary *params = #{#"status": #"Hello, my first autopost tweet..."};
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:#"POST"
URL:statusesShowEndpoint
parameters:params
error:&clientError];
if (request) {
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *dicResponse = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(#"%#",[dicResponse description]);
}
else {
NSLog(#"Error code: %ld | Error description: %#", (long)[connectionError code], [connectionError localizedDescription]);
}
}];
}
else {
NSLog(#"Error: %#", clientError);
}

AFNetworking Error: "Expected status code in (200-299), got 404"

My code:
NSURL *url = [NSURL URLWithString:#"http:testurl.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSString *email = #"test#test.com";
NSString *password = #"test";
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
email, #"email",
password, #"password",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:AFJSONParameterEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
Even though I know the server is expected a POST I tried GET and PUT too and still received the same error. I also have checked the URL 100 times. Any ideas on what's causing the error?
Thanks!!
Go to the URL made by putting http:testurl.com and /myobject together in your browser. 404 means that page or resource does not exist.
Try also moving the slash to the baseUrl, i.e. baseURL to http://testurl.com/ and postPath to myobject see this issue
Your base URL is malformed.
Change this: "http:testurl.com"
To this: "http://testurl.com"

Empty JSON returned by AFNetworking on iOS5

I'm trying to load a simple JSON inside my iPhone app using the AFNetworking library. I'm using two different approaches:
NSURL *url = [NSURL URLWithString:#"http://www.mysite.com/test.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %#", [JSON valueForKeyPath:#"name"]);
} failure:^(NSURLRequest* req,NSHTTPURLResponse *req2, NSError *error,id mex) {
NSLog(#"%#", [error description]);
}];
[operation start];
and using AFHttpClient (which would be my favorite,since it has all the features for dealing with my REST API:
NSString *baseurl = #"http://www.mysite.com";
NSString *path = #"/test.json";
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:baseurl]];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
//[client setAuthorizationHeaderWithUsername:#"myusername" password:#"mypassword"];
[client getPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
//NSLog(#"sjson: %#", [JSON valueForKeyPath:#"entries"]);
NSLog(#"sjson: %#", JSON);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error Code: %i - %#",[error code], [error localizedDescription]);
}];
now,the problem: in both cases I'm receiving an empty Json. I've tested the server side and the web-service is giving the right response and the right MIME type (application/json).
I've already checked this discussion https://github.com/AFNetworking/AFNetworking/issues/175
but my target is pointing to 5.0 and ARC is not enabled for the AFNetworking library.
Maybe I'm missing something obvious here,but I cannot fix it at the moment.
Thanks a lot!
Claus