how can I send raw XML posts to a SOAP interface using AFHTTPSessionManager? The following code is a fork from https://github.com/wymsee/cordova-HTTP/blob/master/src/ios/CordovaHttpPlugin.m#L69:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[dictionary setObject:responseObject forKey:#"data"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
[dictionary setObject:errResponse forKey:#"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
This posts multipart/form-data to the given (soap) url. Is it possible to alter the request so that it will send text/xml with a raw body?
Thanks!
I came up with the following solution to my problem:
NSString *url = [command.arguments objectAtIndex:0];
NSData *body = [[command.arguments objectAtIndex:2] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *headers = [command.arguments objectAtIndex:3];
CordovaHttpPlugin* __weak weakSelf = self;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:url parameters:nil error:nil];
[req setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"text/xml" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:body];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// Append headers
for (NSString* key in headers) {
NSString *value = [headers objectForKey:key];
[req setValue:value forHTTPHeaderField:key];
}
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSDictionary *responseHeaders = [(NSHTTPURLResponse *)response allHeaderFields];
long status = (long) [(NSHTTPURLResponse *) response statusCode];
NSLog(#"Status: %ld", status);
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInteger:status] forKey:#"status"];
[dictionary setObject:responseHeaders forKey:#"headers"];
if (!error) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"POST SUCCESS: %#", responseString);
//[self setResults: dictionary withTask: task];
[dictionary setObject:responseString forKey:#"data"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} else {
//[self setResults: dictionary withTask: task];
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
[dictionary setObject:errResponse forKey:#"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}] resume];
Related
I'm trying to POST request using AFNetworking 3.0.
So far i did not find the exact answer for this issue. Either i don't understand or some of the code is deprecated.
Error is "dataTaskWithRequest is deprecated"
I have this two (2) textfield that need to be post into web server.
1. email
2. pw
So far it didn't work. The current code as below
#import "ViewController.h"
#import "AFNetworking.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize email,pw;
- (IBAction)sendData:(id)sender {
NSString *URLString = #"http://localhost/test.php";
NSDictionary *parameters =#{#"email" : #"pw"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:URLString parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"email"] longValue];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]]) {
NSLog(#"Response == %#",responseObject);
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}]resume];
}
#end
NSString *URLString = #"http://localhost/test.php";
NSDictionary *parameters =#{#"email":#"pass email id" #"pw":#"pass password"};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/x-www-form-urlencoded"];
[manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Aleksi"
message:[error localizedDescription]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
NSLog(#"error=%#",error );
CFRunLoopStop(CFRunLoopGetCurrent());
}];
download Afnetworking 3.0 in this link https://github.com/AFNetworking/AFNetworking
try this code, i guess it will solve your issue
NSString *url = #"http://localhost/test.php";
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
email, #"email",
password, #"pw",
nil
];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//you can change timeout value as per your requirment
[manager.requestSerializer setTimeoutInterval:60.0];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
Simply do like following way in AFNetworking 3.0 :
- (IBAction)sendData:(id)sender {
NSString *Loginurl = [NSString stringWithFormat:Your_URL_is_here];
NSDictionary *params = #{#"user_name":username.text,
#"password":password.text,
};
//here we can see parameters which is sent to server
NSLog(#"Sent parameter to server 2 : %#",params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/html",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/plain",nil];
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
// Here we can see response which is coming from server
NSLog(#"Response from server 2 : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionTask *operation, NSError *error)
{
// If Error occur, then this is AlertController Appear
NSLog(#"Error: %#", error);
UIAlertController *Erroralert= [UIAlertController
alertControllerWithTitle:#" Network Connection Failed!!"
message:#"Please try again"
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:Erroralert animated:YES completion:nil];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[self resignFirstResponder];
[Erroralert dismissViewControllerAnimated:YES completion:nil];
}];
[Erroralert addAction: yesButton];
}];
}
Hello everyone I m trying to send two json objects in one request.
Here is what I did so far:
NSDictionary *credentials = [request getCredentials];
NSURL *url = [NSURL URLWithString:#"https://myurl.com"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
req.HTTPMethod = #"POST";
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSData *o = [NSJSONSerialization dataWithJSONObject:output
options:NSJSONWritingPrettyPrinted error:&error];
NSData *c = [NSJSONSerialization dataWithJSONObject:credentials
options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:o encoding:NSUTF8StringEncoding];
NSLog(#"DATA: %#",myString);
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:req
fromData:c completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSLog(#"RESPONSE %#", response);
}];
[uploadTask resume];
}
In this code I send only "NSData *c" but also I want to send "NSData *o" in the same request. Is it possible, I need your helps. Thanks.
you can combine dictonaries into one using below code then post to server.
#property (nonatomic, strong) NSMutableDictionary *configuration;
...
-(NSMutableDictionary*) configuration{
if (!_configuration) {
NSDictionary *core_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"installation" ofType:#"plist"]];
NSDictionary *app_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:#"/path/to"] pathForResource:#"something/data" ofType:#"plist"]];
[_configuration addEntriesFromDictionary: core_config];
[_configuration addEntriesFromDictionary: app_config];
NSLog(#"merged: %lu, core: %lu, app: %lu", (unsigned long)[_configuration count], (unsigned long)[core_config count], (unsigned long)[app_config count]);
// merged: 0, core: 4, app: 5
}
return _configuration;
}
I need to integrate SMS Verification using Twilio url.
I have ACCOUNT_SID,AUTH_TOKEN and url but not able to parse using Objective C.
CODE:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSString *post = [NSString stringWithFormat:#"From='number'To=%#&Body=message %d to verify your mobile number.",txt_otp.text,[[self sms_verification_code]intValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twilio.com/2010-04-01/Accounts/(SID)/SMS/Messages"]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *authStr = [NSString stringWithFormat:#"SID:TOKEN"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[[session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"SMS verification%#",responseDictionary);
}
}] resume];
I have succeeded parsing using AFNetworking SDK.
NSString *kTwilioSID = #"sid";
NSString *kTwilioSecret = #"token";
NSString *kFromNumber = #"";
NSString *kToNumber =#"";
NSString *kMessage = [NSString stringWithFormat:#"message %d",[[self sms_verification_code] intValue]];
NSString *urlString = [NSString
stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages/",
kTwilioSID, kTwilioSecret,kTwilioSID];
NSDictionary*
dic=#{#"From":kFromNumber,#"To":kToNumber,#"Body":kMessage};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"application/xml"];
[manager POST:urlString parameters:dic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"success %#",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
completion:nil];
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I'm trying to build and login and logout application, but not able to login please help me to set default user id and password through which i would be able go to the next page
You can try this code it will help you :
-(void)login
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://www.example.com/pm/api/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
if(checkBoxSelected == YES)
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernameField.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordField.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self.navigationController pushViewController:i animated:YES];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected;
[checkbox setSelected:checkBoxSelected];
}
to set a default user in app you may use the code below
In your AppDelegate.m
if ([[NSUserDefaults standardUserDefaults]boolForKey:#"IsFirstTime"])
{
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
ViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"ViewController"];
self.window.rootViewController = vc;
}
else
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"IsFirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
then #import your AppDelegate.m class to the class where you put code for login
AppDelegate *delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
}
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://43.252.88.251/jsonandroid/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernamefield.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordfield.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
/* ItemManagement *ItemManagement = [[ItemManagement alloc]init];
[self.navigationController pushViewController:ItemManagement animated:YES];
*/
}
else
{
NSLog(#"Unsuccessful, Try again.");
/* UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];*/
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"Hello" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelbutton = [UIAlertAction actionWithTitle:#"" style:UIAlertActionStyleCancel handler:nil];
//UIAlertAction *oktext= [UIAlertAction actionWithTitle:oktext style:UIAlertActionStyleDefault handler:nil];
[alert addAction:cancelbutton];
//[alert addAction:oktext];
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
How to upload video on facebook using facebook sdk 4.6 on iOS8.This is the code i used:
FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:params tokenString:token.tokenString version:#"nil" HTTPMethod:#"POST" ];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"%#", error);
else
NSLog(#"Success");
}];
[connection start];
any help appreciated.
Try this code. it works for me.
NSDictionary *dictPrivacy = [NSDictionary
dictionaryWithObjectsAndKeys:#"FRIENDS_OF_FRIENDS",#"value",
nil];
SBJSON *jsonWriter = [SBJSON new];
NSString *strPrivacy = [jsonWriter stringWithObject:dictPrivacy];
NSString *Url = [[NSBundle mainBundle] pathForResource:#"Video" ofType:#"MOV"];
NSData *videoData = [NSData dataWithContentsOfFile: videoUrl];
//NSData *videoData = [NSData dataWithContentsOfFile:rtfUrl];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
csString, #"title",
strPrivacy,#"privacy",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (error)
{
NSLog(#"fail to upload over Facebook");
}
else
{
NSLog(#"Successfully uploaded over Facebook");
}
}];
In Graph APi 2.3+
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
[FBSDKShareAPI shareWithContent:content delegate:self];
NOTE: Video URL should be Assest URL.
If one don't want to use FBSDKShareVideo.
- (void)shareVideoOnFacebook:(NSString*)videoURL{
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]){
NSData *videoData = [NSData dataWithContentsOfFile:videoURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#" ", #"title",
#" ", #"description",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error){
if (!error){
NSLog(#"sharing result = %#",result);
}
else{
NSLog(#"error=%#",error.localizedDescription);
}
}];
} else{
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
loginManager.loginBehavior = FBSDKLoginBehaviorNative;
[loginManager logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error || result.isCancelled) {
NSLog(#"fb error= %#",error.localizedDescription);
}
else{
NSData *videoData = [NSData dataWithContentsOfFile:videoURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#" ", #"title",
#" ", #"description",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error){
if (!error){
NSLog(#"sharing result = %#",result);
}else{
NSLog(#"error=%#",error.localizedDescription);
}
}];
}
}];
}
}