Guest User

Untitled

a guest
Oct 23rd, 2017
68
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  2. [request setPostValue:height forKey:@"user[height]"];
  3. [request setPostValue:weight forKey:@"user[weight]"];
  4. [request setDelegate:self];
  5. [request startAsynchronous];
  6.  
  7. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  8. NSDictionary *params = @{@"user[height]": height,
  9. @"user[weight]": weight};
  10. [manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
  11. NSLog(@"JSON: %@", responseObject);
  12. } failure:^(NSURLSessionTask *operation, NSError *error) {
  13. NSLog(@"Error: %@", error);
  14. }];
  15.  
  16. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  17. NSDictionary *params = @{@"user[height]": height,
  18. @"user[weight]": weight};
  19. [manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
  20. NSLog(@"JSON: %@", responseObject);
  21. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  22. NSLog(@"Error: %@", error);
  23. }];
  24.  
  25. NSURL *url = [NSURL URLWithString:@"https://example.com/"];
  26. AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
  27.  
  28. NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
  29. height, @"user[height]",
  30. weight, @"user[weight]",
  31. nil];
  32. [httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
  33. NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  34. NSLog(@"Request Successful, response '%@'", responseStr);
  35. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  36. NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
  37. }];
  38.  
  39. NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
  40. height, @"user[height]",
  41. weight, @"user[weight]",
  42. nil];
  43.  
  44. AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
  45. [NSURL URLWithString:@"http://localhost:8080/"]];
  46.  
  47. [client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
  48. NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  49. NSLog(@"Response: %@", text);
  50. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  51. NSLog(@"%@", [error localizedDescription]);
  52. }];
  53.  
  54. // Add this to the class you're working with - (id)init {}
  55. _netInst = [MyApiClient sharedAFNetworkInstance];
  56.  
  57. // build the dictionary that AFNetworkng converts to a json object on the next line
  58. // params = {"user":{"email":emailAddress,"password":password}};
  59. NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
  60. userName, @"email", password, @"password", nil];
  61. NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
  62. parameters, @"user", nil];
  63.  
  64. [_netInst postPath: @"users/login.json" parameters:params
  65. success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
  66. NSLog (@"SUCCESS");
  67.  
  68. // jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
  69. _accessId = [jsonResponse valueForKeyPath:@"user.accessid"];
  70. _securityKey = [jsonResponse valueForKeyPath:@"user.securitykey"];
  71.  
  72. return SUCCESS;
  73. }
  74. failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  75. NSLog(@"FAILED");
  76.  
  77. // handle failure
  78.  
  79. return error;
  80. }
  81. ];
  82.  
  83. AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://urlname"]];
  84. NSDictionary * parameters = [[NSMutableDictionary alloc] init];
  85. parameters = [NSDictionary dictionaryWithObjectsAndKeys:
  86. height, @"user[height]",
  87. weight, @"user[weight]",
  88. nil];
  89.  
  90. [Client setParameterEncoding:AFJSONParameterEncoding];
  91. [Client postPath:@"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
  92. NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
  93.  
  94. NSLog(@"response string: %@ ", operation.responseString);
  95.  
  96. NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
  97. if ([[jsonResponseDict objectForKey:@"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
  98. NSMutableDictionary *responseBody = [jsonResponseDict objectForKey:@"responseBody"];
  99. //get the response here
  100.  
  101.  
  102. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  103.  
  104. NSLog(@"error: %@", operation.responseString);
  105. NSLog(@"%d",operation.response.statusCode);
  106.  
  107. }];
  108.  
  109. let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
  110. manager = AFHTTPSessionManager(sessionConfiguration: configutation)
  111.  
  112. let urlString = "url"
  113. manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
  114. print(dataTask)
  115. print(response)
  116. }) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
  117. print(error)
  118. }
  119.  
  120. NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
  121. NSDictionary *dictParamiters = @{@"user[height]": height,@"user[weight]": weight};
  122.  
  123. NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];
  124.  
  125. NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
  126.  
  127. NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
  128. [aRequest setHTTPMethod:@"POST"];
  129. [aRequest setHTTPBody:aData];
  130.  
  131. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  132. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
  133. [aRequest setHTTPBody:aData];
  134.  
  135. NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  136. //
  137. if (error ==nil) {
  138. NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  139. NSLog(@"ResponseString:%@",aStr);
  140. NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
  141. dispatch_async(dispatch_get_main_queue(), ^{
  142. completionBlock(aMutDict);
  143.  
  144. NSLog(@"responce:%@",aMutDict)
  145.  
  146. });
  147. }
  148. else
  149. {
  150. dispatch_async(dispatch_get_main_queue(), ^{
  151. NSLog(@"error:%@",error.locali)
  152. });
  153. }
  154. }];
  155.  
  156. [postDataTask resume];
  157.  
  158. -(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
  159. {
  160. NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:@""];
  161. for (NSString *aKey in aDict.allKeys) {
  162. [aMutStr appendFormat:@"%@=%@&",aKey,aDict[aKey]];
  163. }
  164. NSString *aStrParam;
  165. if (aMutStr.length>2) {
  166. aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
  167.  
  168. }
  169. else
  170. aStrParam = @"";
  171.  
  172. return aStrParam;
  173. }
  174.  
  175. NSURL *URL = [NSURL URLWithString:@"url"];
  176.  
  177.  
  178. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  179. NSDictionary *params = @{@"prefix":@"param",@"prefix":@"param",@"prefix":@"param"};
  180. [manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
  181. self.arrayFromPost = [responseObject objectForKey:@"data"];
  182. // values in foreach loop
  183.  
  184.  
  185. NSLog(@"POst send: %@",_arrayFromPost);
  186. } failure:^(NSURLSessionTask *operation, NSError *error) {
  187.  
  188.  
  189. NSLog(@"Error: %@", error);
  190. }];
  191.  
  192. NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
  193. [dictParam setValue:@"VALUE_NAME" forKey:@"KEY_NAME"]; //set parameters like id, name, date, product_name etc
  194.  
  195. if ([[AppDelegate instance] checkInternetConnection]) {
  196. NSError *error;
  197. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParam options:NSJSONWritingPrettyPrinted error:&error];
  198.  
  199. if (jsonData) {
  200. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"Api Url"]
  201. cachePolicy:NSURLRequestReloadIgnoringCacheData
  202. timeoutInterval:30.0f];
  203. [request setHTTPMethod:@"POST"];
  204.  
  205. [request setHTTPBody:jsonData];
  206. [request setValue:ACCESS_TOKEN forHTTPHeaderField:@"TOKEN"];
  207.  
  208. AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  209. op.responseSerializer = [AFJSONResponseSerializer serializer];
  210. op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
  211.  
  212. [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  213. arrayList = [responseObject valueForKey:@"data"];
  214. [_tblView reloadData];
  215. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  216. //show failure alert
  217. }];
  218. [op start];
  219. }
  220. } else {
  221. [UIAlertView infoAlertWithMessage:NO_INTERNET_AVAIL andTitle:APP_NAME];
  222. }
  223.  
  224. let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
  225. manager.requestSerializer = AFJSONRequestSerializer()
  226. manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
  227. manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
  228.  
  229. if authenticated {
  230. if let user = UserDAO.currentUser() {
  231. manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
  232. }
  233. }
  234.  
  235. manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
  236. if var jsonResponse = responseObject as? [String: AnyObject] {
  237. // here read response
  238. }
  239. }) { (task: URLSessionDataTask?, error: Error) in
  240. print("POST fails with error (error)")
  241. }
  242.  
  243. NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter
  244.  
  245. NSString *URLString =@"your url string";
  246.  
  247. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  248. [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
  249. [manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
  250. // [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
  251. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
  252. [manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
  253. {
  254.  
  255. NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
  256.  
  257. NSLog(@"Response DICT:%@",response);
  258.  
  259. if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
  260. {
  261.  
  262. for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
  263. {
  264. [yourNsmutableArray addObject:[dicAll mutableCopy]];
  265. }
  266. //yourNsmutableArray Nsmutablearray alloction in view didload
  267.  
  268. NSLog(@"yourNsmutableArray %@",yourNsmutableArray);
  269. }
  270. else
  271. {
  272. NSLog(@"False");
  273. }
  274.  
  275. [SVProgressHUD dismiss];
  276.  
  277. } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
  278. {
  279. NSLog(@"RESPONSE STRING:%@",task.response);
  280. NSLog(@"error userInfo:%@",error.userInfo);
  281.  
  282. NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
  283. NSLog(@"URLString :--->> %@ Error********* %@",URLString,errResponse);
  284.  
  285. [SVProgressHUD dismiss];
  286.  
  287. }];
  288.  
  289. AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
  290. [manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
  291. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
  292. [manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  293. if (Imagedata.length>0) {
  294. [formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
  295. }
  296. } progress:nil
  297. success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
  298. {
  299. NSLog(@"update_profile %@", responseObject);
  300.  
  301. if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
  302. {
  303. [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
  304. [self.navigationController popViewControllerAnimated:YES];
  305.  
  306. }] animated:YES completion:nil];
  307.  
  308.  
  309. }
  310. else
  311. {
  312. [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
  313. }] animated:YES completion:nil];
  314.  
  315. }
  316. [SVProgressHUD dismiss];
  317.  
  318. } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
  319. {
  320. [SVProgressHUD dismiss];
  321. }];
  322.  
  323. please try below answer.
  324.  
  325. +(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl
  326. withBlock:(dictionary)block
  327. {
  328. AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  329. [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  330. manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  331. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
  332. [manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
  333. {
  334. if (!responseObject)
  335. {
  336. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  337. [dict setObject:ServerResponceError forKey:@"error"];
  338. block(responseObject);
  339. return ;
  340. }
  341. else if ([responseObject isKindOfClass:[NSDictionary class]]) {
  342. block(responseObject);
  343. return ;
  344. }
  345. }
  346. failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
  347. {
  348. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  349. [dict setObject:ServerResponceError forKey:@"error"];
  350. block(dict);
  351. }];
  352. }
  353.  
  354. NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
  355. NSURL * urlStr = [NSURL URLWithString:strURL];
  356.  
  357. NSDictionary *dictParameters = @{@"user[height]": height,@"user[weight]": weight};
  358.  
  359. AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
  360.  
  361.  
  362. [manager GET:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
  363. NSLog(@"PLIST: %@", responseObject);
  364.  
  365. } failure:^(NSURLSessionTask *operation, NSError *error) {
  366. NSLog(@"Error: %@", error);
  367.  
  368. }];
RAW Paste Data