Upload image with post -ios - ios

i use this method to save user informations in data base. Can someone help me to upload image too in the same function ?
- (void)Inscription:(NSArray *)value completion:(void (^)( NSString * retour))block{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSArray *Param_header = #[#"username", #"password", #"email",#"first_name", #"last_name"];
// NSArray *Param_value = #[#"ali", #"aliiiiiiii", #"ali.ali#gmail.com",#"ali",#"zzzzz"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:// /Messenger/services/messenger_register"]]];
NSString *aa=[self buildParameterWithPostType:#"User" andParameterHeaders:Param_header ansParameterValues:value];
[request setHTTPBody:[aa dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
NSError *error = Nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block([NSString stringWithFormat:#"%#", [jsonObjects objectForKey:#"message"]]);
}
}
];
}

You can use third-party frameworks like AFN to upload image。
Here is sample code:
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[#"username"] = #"Jack";
[mgr POST:#"http:// /Messenger/services/messenger_register" parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *file = [[NSBundle mainBundle] pathForResource:#"image.png" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:file];
[formData appendPartWithFileData:data name:#"file" fileName:#"image.png" mimeType:#"mage/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"upload success!----%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"upload failed!----%#", error);
}];

Related

AFNetworking 3 - objective c - send data without key [duplicate]

I am trying to make an HTTP PUT request using AFNetworking to create an attachment in a CouchDB server. The server expects a base64 encoded string in the HTTP body. How can I make this request without sending the HTTP body as a key/value pair using AFNetworking?
I began by looking at this method:
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
But here the parameters are to be of type: NSDictionary. I just want to send a base64 encoded string in the HTTP body but not associated with a key. Can someone point me to the appropriate method to use? Thanks!
Hejazi's answer is simple and should work great.
If, for some reason, you need to be very specific for one request - for example, if you need to override headers, etc. - you can also consider building your own NSURLRequest.
Here's some (untested) sample code:
// Make a request...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
// Generate an NSData from your NSString (see below for link to more info)
NSData *postBody = [NSData base64DataFromString:yourBase64EncodedString];
// Add Content-Length header if your server needs it
unsigned long long postLength = postBody.length;
NSString *contentLength = [NSString stringWithFormat:#"%llu", postLength];
[request addValue:contentLength forHTTPHeaderField:#"Content-Length"];
// This should all look familiar...
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
The NSData category method base64DataFromString is available here.
You can use multipartFormRequestWithMethod method as following:
NSURLRequest *request = [self multipartFormRequestWithMethod:#"PUT" path:path parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
[formData appendString:<yourBase64EncodedString>]
}];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
Here you have an example sending a raw json:
NSDictionary *dict = ...
NSError *error;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:YOUR_URL parameters:nil error:nil];
req.timeoutInterval = 30;
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:IF_NEEDED forHTTPHeaderField:#"Authorization"];
[req setHTTPBody:dataFromDict];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"%#", responseObject);
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
NSData *data = someData;
NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:[self getURLWith:urlService]]];
[reqeust setHTTPMethod:#"PUT"];
[reqeust setHTTPBody:data];
[reqeust setValue:#"application/raw" forHTTPHeaderField:#"Content-Type"];
NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}];
[task resume];
I'm using AFNetworking 2.5.3 and create new POST method for AFHTTPRequestOperationManager.
extension AFHTTPRequestOperationManager {
func POST(URLString: String!, rawBody: NSData!, success: ((AFHTTPRequestOperation!, AnyObject!) -> Void)!, failure: ((AFHTTPRequestOperation!, NSError!) -> Void)!) {
let request = NSMutableURLRequest(URL: NSURL(string: URLString, relativeToURL: baseURL)!)
request.HTTPMethod = "POST"
request.HTTPBody = rawBody
let operation = HTTPRequestOperationWithRequest(request, success: success, failure: failure)
operationQueue.addOperation(operation)
}
}
Please use below method.
+(void)callPostWithRawData:(NSDictionary *)dict withURL:(NSString
*)strUrl withToken:(NSString *)strToken withBlock:(dictionary)block
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
Please use below method.
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#/%#",WebserviceUrl,strUrl] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[req setValue:strToken forHTTPHeaderField:#"Authorization"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
if ([responseObject isKindOfClass:[NSData class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if ((long)[httpResponse statusCode]==201) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"201" forKey:#"Code"];
if ([httpResponse respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(#"%#",[dictionary objectForKey:#"Location"]);
[dict setObject:[NSString stringWithFormat:#"%#",[dictionary objectForKey:#"Location"]] forKey:#"Id"];
block(dict);
}
}
else if ((long)[httpResponse statusCode]==200) {
//Leave Hours Calculate
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
block(serializedData);
}
else{
}
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
}
} else {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(dict);
}
}] resume];
}

afnetworking 3.0 Migration: how to POST with headers and HTTP Body

I am trying to make a POST request which has HTTPHeader Fields and a HTTP body to the youtube API.
Previously in version 2.0 of AFNetworking, I used to do it this way which worked:
NSDictionary *parameters = #{#"snippet": #{#"textOriginal":self.commentToPost.text,#"parentId":self.commentReplyingTo.commentId}};
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/comments?part=snippet&access_token=%#",[[LoginSingleton sharedInstance] getaccesstoken]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Reply JSON: %#", responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#, %#, %#, %#, %#", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);
}];
[operation start];
The migration docs for version 3.0 replaces AFHTTPRequestOperationManager with AFHTTPSessionManager
However I can't seem to find a HTTPRequestOperationWithRequest method for the AFHTTPSessionManager.
I tried using the constructingBodyWithBlock but it doesn't work maybe because I am not doing it correctly.
This is what I have so far which doesn't work:
NSDictionary *body = #{#"snippet": #{#"topLevelComment":#{#"snippet":#{#"textOriginal":self.commentToPost.text}},#"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
serializer.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:[NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%#",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithHeaders:nil body:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Reply JSON: %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error: %#, %#, %#, %#, %#", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);
}];
Another way to call a POST method with AFNetworking 3.0 is:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"success!");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
}];
Hope it helps!
I was able to figure this out myself.
Here's the solution.
First, you need to create the NSMutableURLRequest from AFJSONRequestSerializer first where you can set the method type to POST.
On this request, you get to setHTTPBody after you have set your HTTPHeaderFields. Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error.
Then on the manager create a dataTaskWithRequest using the above NSMutableURLRequest. Don't forget to resume the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully:
NSDictionary *body = #{#"snippet": #{#"topLevelComment":#{#"snippet":#{#"textOriginal":self.commentToPost.text}},#"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body 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:[NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%#",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" 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:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
Accepted answer of #Pranoy C is converted for AFNetworking 3.0
NSError *writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json; encoding=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue: #"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#", error);
NSLog(#"Response: %#",response);
NSLog(#"Response Object: %#",responseObject);
}
}] resume];
For HTTPBody with JSON
[sessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return argString;
}];
[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (completion) {
completion(responseObject, nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (completion) {
NSData *errorData = [error.userInfo objectForKey:#"com.alamofire.serialization.response.error.data"];
NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
completion(responseErrorObject, error);
}
}];
For HTTPBody with custom String format
[sessionManager.requestSerializer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
NSString *argString = [self dictionaryToString:parameters];
return argString;
}];
[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (completion) {
completion(responseObject, nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (completion) {
NSData *errorData = [error.userInfo objectForKey:#"com.alamofire.serialization.response.error.data"];
NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
completion(responseErrorObject, error);
}
}];
-(void)postRequest:(NSString *)urlStr parameters:(NSDictionary *)parametersDictionary completionHandler:(void (^)(NSString*, NSDictionary*))completionBlock{
NSURL *URL = [NSURL URLWithString:urlStr];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:URL.absoluteString parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
completionBlock(#"Success",json);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
completionBlock(#"Error",nil);
}];
}
This method is working fine for AFNetworking 3.0.
Use common NSObject Class method for Calling Wenservices with AFNetworking 3.0
This is my Duplicate Answer but it was Updated with AFNetworking 3.0
First make NSObject Class Like Webservice.h and Webservice.m
Webservice.h
#interface Webservice : NSObject
+ (void)requestPostUrl:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure;
#end
Webservice.m your nsobject.m file is look like this.(add two functions in .m file)
#import "Webservice.h"
#define kDefaultErrorCode 12345
#implementation Webservice
+ (void)requestPostUrl:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager POST:strURL parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
success(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(success) {
success(response);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure) {
failure(error);
}
}];
}
#end
make sure you have to replace your dictionary key with success and
message for handling of responce callback function
Use like this call this common method from any viewcontroller.m and any methods from any viewControllers. for temporary i am using viewDidLoad for calling This WS.
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *dictParam = #{#"parameter1":#"value1",#"parameter1":#"value2"};
[Webservice requestPostUrl:#"add your webservice URL here" parameters:dictParam success:^(NSDictionary *responce) {
//Success
NSLog(#"responce:%#",responce);
//do code here
} failure:^(NSError *error) {
//error
}];
}
add your Parameter, values and webservice URL in above method. you can easily use this NSObjcet Class. for more details please visit AFNetworking 3.0 or my old answear with AFNetworking 2.0.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:log.text, #"email", pass.text, #"password", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:#"add your webservice URL here" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
/**
* Services gateway
* Method get response from server
* #parameter -> object: request josn object ,apiName: api endpoint
* #returm -> void
* #compilationHandler -> success: status of api, response: respose from server, error: error handling
*/
+ (void)getDataWithObject:(NSDictionary *)object onAPI:(NSString *)apiName withController:(UIViewController*)controller
:(void(^)(BOOL success,id response,NSError *error))compilationHandler {
controller = controller;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request type to json
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// post request to server
[manager POST:apiName parameters:object success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject
options:0
error:&error];
//NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
////
// check the status of API
NSDictionary *dict = responseObject;
NSString *statusOfApi = [[NSString alloc]initWithFormat:#"%#"
,[dict objectForKey:#"OK"]];
// IF Status is OK -> 1 so complete the handler
if ([statusOfApi isEqualToString:#"1"] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
compilationHandler(TRUE,responseObject,nil);
} else {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *errorMessages = [responseObject objectForKey:#"messages"];
NSString *message = [errorMessages objectAtIndex:0];
[Utilities showAlertViewWithTitle:apiName message:message];
compilationHandler(FALSE,responseObject,nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *message = [NSString stringWithFormat:#"%#",[error localizedDescription]];
NSLog(#"Message is %#", message);
NSString *errorMessage = [NSString stringWithFormat:#"%#",[error localizedDescription]];
if (!([message rangeOfString:#"The request timed out."].location == NSNotFound)) {
[Utilities showAlertViewWithTitle:apiName message:errorMessage];
}
compilationHandler(FALSE,errorMessage,nil);
}];
}
- (instancetype)init {
self = [super init];
if (self) {
[self configureSesionManager];
}
return self;
}
#pragma mark - Private
- (void)configureSesionManager {
sessionManager = [AFHTTPSessionManager manager];
sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
sessionManager.requestSerializer.timeoutInterval = 60;
}
#pragma mark - Public
- (void)communicateUsingPOSTMethod:(NSString*)pBaseURL parameterDictionary:(NSDictionary*)pParameterDictionary
success:(void(^)(id))pSuccessCallback failure:(void(^)(NSError* error))pFailiureCallback {
[sessionManager POST:pBaseURL parameters:pParameterDictionary progress:nil success:^(NSURLSessionTask *task, id responseObject) {
pSuccessCallback(responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
pFailiureCallback(error);
}];
}
#import <Foundation/Foundation.h>
#import "UserDetailObject.h"
#import "AFNetworking.h"
#import "XMLReader.h"
//宏定义成功block 回调成功后得到的信息
typedef void (^HttpSuccess)(id data);
//宏定义失败block 回调失败信息
typedef void (^HttpFailure)(NSError *error);
#interface NetworkManager : NSObject<NSXMLParserDelegate, NSURLConnectionDelegate>
#property (strong, nonatomic) NSMutableData *webData;
#property (strong, nonatomic) NSMutableString *soapResults;
#property (strong, nonatomic) NSXMLParser *xmlParser;
#property (nonatomic) BOOL elementFound;
#property (strong, nonatomic) NSString *matchingElement;
#property (strong, nonatomic) NSURLConnection *conn;
//请求水文信息数据
+ (void)sendRequestForSQInfo:(UserDetailObject *)detailObject success:(HttpSuccess)success failure:(HttpFailure)failure;
//get请求
+(void)getWithUrlString:(NSString *)urlString success:(HttpSuccess)success failure:(HttpFailure)failure;
//post请求
+(void)postWithUrlString:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure;
#end
NetworkManager.m
#import "NetworkManager.h"
#implementation NetworkManager
#synthesize webData;
#synthesize soapResults;
#synthesize xmlParser;
#synthesize elementFound;
#synthesize matchingElement;
#synthesize conn;
+ (void)sendRequestForSQInfo:(UserDetailObject *)detailObject success:(HttpSuccess)success failure:(HttpFailure)failure{
NSString *parameter = #"{\"endDate\":\"2015-06-01 08\",\"beginDate\":\"2015-06-01 08\"}";
NSString *urlStr = #"http://10.3.250.136/hwccysq/cxf/water";
NSString *methodName = #"getSqInfo";
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//回复的序列化
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[[manager dataTaskWithRequest:[self loadRequestWithParameter:parameter url:urlStr methodName:methodName] completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
success(responseObject);
} else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
failure(error);
}
}] resume];
}
+ (NSMutableURLRequest *)loadRequestWithParameter:(NSString *)parameter url:(NSString *)urlString methodName:(NSString *)methodName{
NSString *soapMessage =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:agen=\"http://agent.water.tjswfxkh.lonwin.com/\" >"
"<soapenv:Body>"
"<agen:%#>"
"<arg0>%#</arg0>"
"</agen:%#>"
"</soapenv:Body>"
"</soapenv:Envelope>", methodName,parameter,methodName
];
// 将这个XML字符串打印出来
NSLog(#"%#", soapMessage);
// 创建URL,内容是前面的请求报文报文中第二行主机地址加上第一行URL字段
NSURL *url = [NSURL URLWithString:urlString];
// 根据上面的URL创建一个请求
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLengt = [NSString stringWithFormat:#"%ld", [soapMessage length]];
// 添加请求的详细信息,与请求报文前半部分的各字段对应
[req addValue:#"application/soap+xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLengt forHTTPHeaderField:#"Content-Length"];
// 设置请求行方法为POST,与请求报文第一行对应
[req setHTTPMethod:#"POST"];
// 将SOAP消息加到请求中
[req setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
//GET请求
+(void)getWithUrlString:(NSString *)urlString success:(HttpSuccess)success failure:(HttpFailure)failure{
//创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//内容类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/json",#"text/javascript",#"text/html", nil];
//get请求
[manager GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
//POST请求
+(void)postWithUrlString:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure{
//创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//内容类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/json",#"text/javascript",#"text/html", nil];
//post请求
[manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
#end
then add request in controller
UserDetailObject *detailObject = [[UserDetailObject alloc]init];
[NetworkManager sendRequestForSQInfo:detailObject success:^(id data) {
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
NSError *parseError = nil;
NSDictionary *dict = [XMLReader dictionaryForNSXMLParser:parser error:&parseError];
NSLog(#"JSON: - %#", dict);
} failure:^(NSError *error) {
NSLog(#"%#",error);
}];
https://github.com/Rita5969/afnetwork3.0-for-webservice

Send UIImage POST to server from UIImagePickerController?

I am trying to send a UIImage take with the UIImagePickerController to a server POST along with other pertinent values. But I get at the line that tries to set the dictionary value #"image" to UIImageJPEGRepresentation(image, 1.0):
-(void)sendImageToServer:(UIImage *)image
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:nil delegateQueue:queue];
NSURL *uploadURL = [NSURL URLWithString:#"http://...."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *postData = [[NSData alloc] init];
[postData setValue:UIImageJPEGRepresentation(image, 1.0) forKey:#"image"];
[postData setValue:#"1" forKey:#"categories[0]"];
[postData setValue:#"4" forKey:#"categories[1]"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSError *err;
NSDictionary *JSONDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
NSLog(#"HTTP 200 response: %#", JSONDict);
});
} else {
NSLog(#"HTTP %ld status!", (long)httpResponse.statusCode);
}
} else {
NSLog(#"HTTP post image error: %#", error);
}
}];
[uploadTask resume];
}
JSON serialization does not work here, because images are not valid JSON values. If on the other hand I try:
...
NSMutableData *postData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:postData];
[archiver encodeObject:UIImageJPEGRepresentation(image, 1.0) forKey:#"image"];
[archiver encodeObject:#"1" forKey:#"categories[0]"];
[archiver encodeObject:#"4" forKey:#"categories[1]"];
[archiver finishEncoding];
//NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:NSJSONWritingPrettyPrinted error:&jsonError];
//Now you can post the json data
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:postData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {...
The key:value pairs archived do not seem to get to the server as such. This must be a routinely iOS coding task.
Even if I just try:
NSError *jsonError;
NSData *postData = [NSJSONSerialization dataWithJSONObject:#{#"image":#"123",#"categories[0]":#"1",#"categories[1]":#"4"} options:NSJSONWritingPrettyPrinted error:&jsonError];
The server does not get any keys at all...
That's not the proper usage of NSData. It's crashing right now because NSData does not have key named image (..or the other two after that). What you need to do is create an NSDictionary and then convert that to NSData.
Do something like this instead:
NSDictionary *dictionary = [NSDictionary alloc]initWithObjectsAndKeys:image,#"image",#(1),#"categories[0]",#(4),#"categories[1]", nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary]; //Not currently using NSJSONSerialization since you want to post a Dictionary with an invalid NSJSONSerialization type in it.
//Now you can post the json data
Give a try with AFNetworking, it have a great way to make uploads, you can find the samples here: https://github.com/AFNetworking/AFNetworking#creating-an-upload-task
I personally recommend everyone to use it, since I started to use I didn't have any trouble to communicate my apps with webservers.
Use AFNetworking and the multi-part form post. Here is a rough example (note I am passing in a block so your implementation will vary):
AFHTTPRequestOperation *operation = [self POST:FullURLString parameters:Params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:fileData name:fileName fileName:fileName mimeType:mimeType];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData *responseData = [operation responseData];
id retObj;
NSError *error = nil;
if (responseData) {
retObj = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
}
// Pass back the serialized object (either an NSArray of type NSDictionaries or an NSArray of type customClass)
block(retObj);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error = [Error]: %#", error);
block(nil);
}];

How to use AFNetworking to create JSON array

I am currently trying to create a JSON array like I do here like this:
NSURL *url = [NSURL URLWithString:currentJSON];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
if (jsonData) {
result = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
}
Which works fine. Apart from I want it to time out if the internet connection is not great.
So I then wen to AFNetworking where I wrote code like this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:currentJSON parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
result = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingMutableContainers
error:&error];
[[NSUserDefaults standardUserDefaults] setObject:result forKey:#"All"];
[[NSUserDefaults standardUserDefaults] synchronize];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
result = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:#"All"];
}
But this method always runs to a failure How come? What am I doing wrong?
Check that server is sending JSON using correct content type 'application/json'. AFNetowrking checks this out of the box and if receives something else (for example 'text/html'), failure block will be called.
Also AFNetworking does JSON to object parsing out of the box. 'id responseObject' is already the result of '[NSJSONSerialization JSONObjectWithData]'.
If you can't change content type sent by server, you could add that content type to accepted types using following snippet
NSMutableSet *accepted = [NSMutableSet set];
[accepted addObject:#"text/html"];
[accepted addObject:#"application/json"];
manager.responseSerializer.acceptableContentTypes = accepted;
Try this :
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
result = (NSDictionary *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];

AFNetworking Post Request

I'm a newbie in obj-c and have been using asihttp for some of my projects. When doing a post request in asihttp its done this way.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:height forKey:#"user[height]"];
[request setPostValue:weight forKey:#"user[weight]"];
[request setDelegate:self];
[request startAsynchronous];
How would go about doing this is AFNetworking with a code example ?
I already got the get Json getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.
It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.
For AFNetworking 3.0:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For AFNetworking 2.0 (and also using the new NSDictionary syntax):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
If you are stuck using AFNetworking 1.0, you need to do it this way:
NSURL *url = [NSURL URLWithString:#"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:#"http://localhost:8080/"]];
[client postPath:#"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Here is a simple AFNetworking POST I'm using. To get up and running after
reading the AFNetworking doc, wkiki, ref, etc, I learned a lot by
following http://nsscreencast.com/episodes/6-afnetworking and understanding
the associated code sample on github.
// Add this to the class you're working with - (id)init {}
_netInst = [MyApiClient sharedAFNetworkInstance];
// build the dictionary that AFNetworkng converts to a json object on the next line
// params = {"user":{"email":emailAddress,"password":password}};
NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
userName, #"email", password, #"password", nil];
NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
parameters, #"user", nil];
[_netInst postPath: #"users/login.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
NSLog (#"SUCCESS");
// jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
_accessId = [jsonResponse valueForKeyPath:#"user.accessid"];
_securityKey = [jsonResponse valueForKeyPath:#"user.securitykey"];
return SUCCESS;
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"FAILED");
// handle failure
return error;
}
];
For AFNetworking 4
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://example.com/myobject" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://urlname"]];
NSDictionary * parameters = [[NSMutableDictionary alloc] init];
parameters = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[Client setParameterEncoding:AFJSONParameterEncoding];
[Client postPath:#"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(#"response string: %# ", operation.responseString);
NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
if ([[jsonResponseDict objectForKey:#"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
NSMutableDictionary *responseBody = [jsonResponseDict objectForKey:#"responseBody"];
//get the response here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
NSLog(#"%d",operation.response.statusCode);
}];
Hope this works.
Here an example with Swift 3.0
let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
if authenticated {
if let user = UserDAO.currentUser() {
manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
}
}
manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if var jsonResponse = responseObject as? [String: AnyObject] {
// here read response
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];
NSDictionary *dictParam =#{#"user_id":#"31"};// Add perameter
NSString *URLString =#"your url string";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:#"Authorization"];//strGlobalLoginToken is your login token
// [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:#"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html",#"text/plain",#"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Response DICT:%#",response);
if ([[[[response objectForKey:#"response"] objectAtIndex:0] objectForKey:#"status"] isEqualToString:#"true"])
{
for (NSMutableDictionary *dicAll in [[[response objectForKey:#"response"]objectAtIndex:0]objectForKey:#"plans"])
{
[yourNsmutableArray addObject:[dicAll mutableCopy]];
}
//yourNsmutableArray Nsmutablearray alloction in view didload
NSLog(#"yourNsmutableArray %#",yourNsmutableArray);
}
else
{
NSLog(#"False");
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
NSLog(#"RESPONSE STRING:%#",task.response);
NSLog(#"error userInfo:%#",error.userInfo);
NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"URLString :--->> %# Error********* %#",URLString,errResponse);
[SVProgressHUD dismiss];
}];
For AFNetworking 3.0 and Swift. Maybe we can use like this:
let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)
let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
print(dataTask)
print(response)
}) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
print(error)
}
Hope this will help other find answer like me!
For AFNetworking 3.0 (iOS9 or greter)
NSString *strURL = #"https://exampleWeb.com/webserviceOBJ";
NSDictionary *dictParamiters = #{#"user[height]": height,#"user[weight]": weight};
NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];
NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
[aRequest setHTTPMethod:#"POST"];
[aRequest setHTTPBody:aData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
[aRequest setHTTPBody:aData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
if (error ==nil) {
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(aMutDict);
NSLog(#"responce:%#",aMutDict)
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"error:%#",error.locali)
});
}
}];
[postDataTask resume];
and Add
-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:#""];
for (NSString *aKey in aDict.allKeys) {
[aMutStr appendFormat:#"%#=%#&",aKey,aDict[aKey]];
}
NSString *aStrParam;
if (aMutStr.length>2) {
aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
}
else
aStrParam = #"";
return aStrParam;
}
NSURL *URL = [NSURL URLWithString:#"url"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"prefix":#"param",#"prefix":#"param",#"prefix":#"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
self.arrayFromPost = [responseObject objectForKey:#"data"];
// values in foreach loop
NSLog(#"POst send: %#",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
[dictParam setValue:#"VALUE_NAME" forKey:#"KEY_NAME"]; //set parameters like id, name, date, product_name etc
if ([[AppDelegate instance] checkInternetConnection]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParam options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"Api Url"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0f];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
[request setValue:ACCESS_TOKEN forHTTPHeaderField:#"TOKEN"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"text/plain",#"text/html",#"application/json", nil];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
arrayList = [responseObject valueForKey:#"data"];
[_tblView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//show failure alert
}];
[op start];
}
} else {
[UIAlertView infoAlertWithMessage:NO_INTERNET_AVAIL andTitle:APP_NAME];
}
please try below answer.
+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
[manager POST:[NSString stringWithFormat:#"%#/%#",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
if (!responseObject)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(responseObject);
return ;
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
return ;
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(dict);
}];
}
for login screen;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:_usernametf.text, #"username",_passwordtf.text, #"password", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:#"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
// For Image with parameter /// AFMultipartFormData
NSDictionary *dictParam =#{#"user_id":strGlobalUserId,#"name":[dictParameter objectForKey:#"Name"],#"contact":[dictParameter objectForKey:#"Contact Number"]};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:#"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html",#"text/plain",#"application/rss+xml", nil];
[manager POST:#"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (Imagedata.length>0) {
[formData appendPartWithFileData:Imagedata name:#"profile_pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
} progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(#"update_profile %#", responseObject);
if ([[[[responseObject objectForKey:#"response"] objectAtIndex:0] objectForKey:#"status"] isEqualToString:#"true"])
{
[self presentViewController:[global SimpleAlertviewcontroller:#"" Body:[[[responseObject objectForKey:#"response"] objectAtIndex:0] objectForKey:#"response_msg"] handler:^(UIAlertAction *action) {
[self.navigationController popViewControllerAnimated:YES];
}] animated:YES completion:nil];
}
else
{
[self presentViewController:[global SimpleAlertviewcontroller:#"" Body:[[[responseObject objectForKey:#"response"] objectAtIndex:0] objectForKey:#"response_msg"] handler:^(UIAlertAction *action) {
}] animated:YES completion:nil];
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
[SVProgressHUD dismiss];
}];
Using AFNetworking 3.0, you should write:
NSString *strURL = #"https://exampleWeb.com/webserviceOBJ";
NSURL * urlStr = [NSURL URLWithString:strURL];
NSDictionary *dictParameters = #{#"user[height]": height,#"user[weight]": weight};
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
[manager POST:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"PLIST: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources