ios,objective-c,afnetworking-2 , How to send HTTP POST request with AFNetworking?

How to send HTTP POST request with AFNetworking?


Tag: ios,objective-c,afnetworking-2

I have a remote address here:

I need to insert new students via API call.

Here is how I did it with javasript:

var data  = {"name":"Meg",

        type: "POST",
        url: "/students/",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function(){console.log("boo");}

You can go to the URL and use your browser's javascript console in order to check whether it works.

Now, my problem is to do the same thing from Objective C. Here is what I did,

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"name": @"reza"};
[manager POST:@""
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
   // NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);

Now I'm getting the following error:

2015-05-14 01:16:58.568 logintest[20916:722708] 
Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 
"Request failed: client error (422)" UserInfo=0x7fed68e2d430 

"Request failed: unacceptable content-type: text/html", 
 0x7fed68c2b8b0> { URL: } 
{ status code: 422, headers {
Connection = close;
"Content-Length" = 1547;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 13 May 2015 19:16:57 GMT";
Server = "WEBrick/1.3.1 (Ruby/2.0.0/2015-04-13)";
Via = "1.1 vegur";
"X-Request-Id" = "c6ea9bf8-05a6-4497-8585-47d21f59726f";
"X-Runtime" = "1.369345";
} }, NSErrorFailingURLKey=,
<3c21444f 43545950 45206874 6d6c3e0a 3c68746d 6c3e0a3c 68656164 3e0a2020 3c746974 6c653e54 68652063 68616e67 6520796f 75207761 6e746564 20776173 2072656a 65637465 64202834 3232293c 2f746974 6c653e0a 20203c6d 65746120 6e616d65 3d227669 6577706f 72742220 636f6e74 656e743d 22776964 74683d64 65766963 652d7769 6474682c 696e6974 69616c2d 7363616c 653d3122 3e0a2020 3c737479 6c653e0a 2020626f 6479207b 0a202020 20626163 6b67726f 756e642d 636f6c6f 723a2023 45464546 45463b0a 20202020 636f6c6f 723a2023 32453246 33303b0a 20202020 74657874 2d616c69 676e3a20 63656e74 65723b0a 20202020 666f6e74 2d66616d 696c793a 20617269 616c2c20 73616e73 2d736572 69663b0a 20202020 6d617267 696e3a20 303b0a20 207d0a0a 20206469 762e6469 616c6f67 207b0a20 20202077 69647468 3a203935 253b0a20 2020206d 61782d77 69647468 3a203333 656d3b0a 20202020 6d617267 696e3a20 34656d20 6175746f 20303b0a 20207d0a 0a202064 69762e64 69616c6f 67203e20 64697620 7b0a2020 2020626f 72646572 3a203170 7820736f 6c696420 23434343 3b0a2020 2020626f 72646572 2d726967 68742d63 6f6c6f72 3a202339 39393b0a 20202020 626f7264 65722d6c 6566742d 636f6c6f 723a2023 3939393b 0a202020 20626f72 6465722d 626f7474 6f6d2d63 6f6c6f72 3a202342 42423b0a 20202020 626f7264 65722d74 6f703a20 23423030 31303020 736f6c69 64203470 783b0a20 20202062 6f726465 722d746f 702d6c65 66742d72 61646975 733a2039 70783b0a 20202020 626f7264 65722d74 6f702d72 69676874 2d726164 6975733a 20397078 3b0a2020 20206261 636b6772 6f756e64 2d636f6c 6f723a20 77686974 653b0a20 20202070 61646469 6e673a20 37707820 31322520 303b0a20 20202062 6f782d73 6861646f 773a2030 20337078 20387078 20726762 61283530 2c203530 2c203530 2c20302e 3137293b 0a20207d 0a0a2020 6831207b 0a202020 20666f6e 742d7369 7a653a20 31303025 3b0a2020 2020636f 6c6f723a 20233733 30453135 3b0a2020 20206c69 6e652d68 65696768 743a2031 2e35656d 3b0a2020 7d0a0a20 20646976 2e646961 6c6f6720 3e207020 7b0a2020 20206d61 7267696e 3a203020 30203165 6d3b0a20 20202070 61646469 6e673a20 31656d3b 0a202020 20626163 6b67726f 756e642d 636f6c6f 723a2023 46374637 46373b0a 20202020 626f7264 65723a20 31707820 736f6c69 64202343 43433b0a 20202020 626f7264 65722d72 69676874 2d636f6c 6f723a20 23393939 3b0a2020 2020626f 72646572 2d6c6566 742d636f 6c6f723a 20233939 393b0a20 20202062 6f726465 722d626f 74746f6d 2d636f6c 6f723a20 23393939 3b0a2020 2020626f 72646572 2d626f74 746f6d2d 6c656674 2d726164 6975733a 20347078 3b0a2020 2020626f 72646572 2d626f74 746f6d2d 72696768 742d7261 64697573 3a203470 783b0a20 20202062 6f726465 722d746f 702d636f 6c6f723a 20234441 44414441 3b0a2020 2020636f 6c6f723a 20233636 363b0a20 20202062 6f782d73 6861646f 773a2030 20337078 20387078 20726762 61283530 2c203530 2c203530 2c20302e 3137293b 0a20207d 0a20203c 2f737479 6c653e0a 3c2f6865 61643e0a 0a3c626f 64793e0a 20203c21 2d2d2054 68697320 66696c65 206c6976 65732069 6e207075 626c6963 2f343232 2e68746d 6c202d2d 3e0a2020 3c646976 20636c61 73733d22 6469616c 6f67223e 0a202020 203c6469 763e0a20 20202020 203c6831 3e546865 20636861 6e676520 796f7520 77616e74 65642077 61732072 656a6563 7465642e 3c2f6831 3e0a2020 20202020 3c703e4d 61796265 20796f75 20747269 65642074 6f206368 616e6765 20736f6d 65746869 6e672079 6f752064 69646e27 74206861 76652061 63636573 7320746f 2e3c2f70 3e0a2020 20203c2f 6469763e 0a202020 203c703e 49662079 6f752061 72652074 68652061 70706c69 63617469 6f6e206f 776e6572 20636865 636b2074 6865206c 6f677320 666f7220 6d6f7265 20696e66 6f726d61 74696f6e 2e3c2f70 3e0a2020 3c2f6469 763e0a3c 2f626f64 793e0a3c 2f68746d 6c3e0a>,
 NSLocalizedDescription=Request failed: client error (422)}

Is this csrf token related problem? How can I send POST request from my objective C code?

You can see my code here

I can use the following CURL command

 curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d "{\"student\":{\"name\":\"Choity\",\"regi_number\":\"10000\"}}"


This problem was happening because I didn't add the HTTP Header parameter "Accept". So the following line was missing [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

On the other hand I changed the backend in order to preventing it of generating the csrf token while requesting via json by this code

skip_before_action :verify_authenticity_token,
                 :if => { |c| c.request.format == 'application/json' }

The forntent code looks like this now:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
 [manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
 [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

  NSDictionary *parameters = @{@"student":@{@"name":@"Reyan",@"regi_number":@"55"}};
 [manager POST:@""

   parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);

I can test with CURL command too:

 curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d "{\"student\":{\"name\":\"Choity\",\"regi_number\":\"10000\"}}"


After an insert into the UITableView : custom the cell

I'm using insertion into my UITableView with this : Skill * newSkill = [[Skill alloc] init]; = @"Nouvelle compétence"; newSkill.pathPicto = @"generic"; [self.skills insertObject:newSkill atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationTop]; [self.tableView endUpdates]; It works great but now I want that the inserted cell be...

Call method after asynchronous request obj-c

In my app I init a new object, where there is method which calls NSURLConnection's sendAsynchronousRequest method. After the request, I would like to call a method in the caller UIViewController. I tried to use a static method but I then I can't control IBOutlets. How can I do this?...

Build error after I localized Info.plist

I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

NS_ENUM as property in protocol

I came across to strange behaviour. I used to have: @property (nonatomic) ApplicationState applicationState; directly in my Application class. Now it's extracted to protocol @protocol ApplicationProtocol <NSObject> @property (nonatomic) ApplicationState applicationState; ApplicationState is Enum typedef NS_ENUM(NSUInteger, ApplicationState) { ApplicationStateNormal = 0, ApplicationStateExpanded = 1, ApplicationStateMaximized = 2 }; Now. It...

Implementing Applovin Ads with Swift & SpriteKit

I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

UITapGestureRecognizer sender is the gesture, not the ui object

I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

Unexpectedly found nil while unwrapping an Optional value - Plist

i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

Cursor doesn't update in NSTextField as it autoresizes when resizing the enclosing NSWindow

I have an NSTextField that autoresizes. Its text is centered. When I start typing in the field and then resize the enclosing NSWindow, the cursor stays where it's at rather than repositioning to the appropriate place : I've also made an XCode project demonstrating this problem : Does anyone...

animating a view on top of uitableview

I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

How can I fix crash when tap to select row after scrolling the tableview?

I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...

Transferring an Xcode project to another computer with all files/frameworks

I am trying to copy over my Xcode project from one computer to another but it seems to lose frameworks and the locations for the images although i copied those too. PS I am using xcode and coding an app with a friend. Is there a useful source that can...

Getting video from Asset Catalog using On Demand ressources

I attributed to my .mp4 video the "tokyo" tag for example, and set it as installed during the app installation. Now before I was using a Path to get it from my resources, now it's different because it's located on the Asset Catalog. After found documentations, I tried something like...

Characters and Strings in Swift

Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways: let narrowNonBreakingSpace: Character = "\u{202f}" let narrowNonBreakingSpace = "\u{202f}" As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

ios8 Timezone parsing changed?

Has the parsing for timzones changed in iOS8? I try to parse the date "2014-09-03 12:20:38.000 +0200" with this code and get nil: -(NSDateFormatter*) dateAndTimeFormatter{ if(!_dateAndTimeFormatter){ _dateAndTimeFormatter = [[NSDateFormatter alloc]init]; [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZZZ"]; _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle; _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle; } return _dateAndTimeFormatter; } alternatively [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd...

try to recover views from custom cell

I made a custom cell from my storyboard, with an UIImageView and a UILabel. Each of them have a tag 100 for the imageView and 102 for UILabel. I try to get them in my datasource method but as below, they are still nil and I don't know why. ...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

How to create UITableViewCells with complex content in order to keep scrolling fluent

I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

How to get time difference based on GMT on Swift

I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

How can I show ONLY the date (and not the time) using NSDateFormatter?

I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

IOS - Adjust cell height based on content

im trying to build apps that have tableview cell similiar with twitter, there are text and images. My problem is i want to insert the image above the text. While it can be text only. So if there are no image, the text will be in position (0,0). And if...

Difference between stringByAppendingString and appendString in ios

What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

SpriteKit collision angle of line and circle is odd

Suppose a circle is enclosed in a diamond, and the circle heads due right. I would expect a series of continual 90 degree angles as the circle draws a square within the diamond. What I'm seeing, however, is that the circle eventually gets pushed toward the center of the diamond...

Scaling everything up and down for different devices in UIStoryboard

Is it possible to have the storyboard scale everything up or down depending on the screen size or do I have to do it programmatically? For example the UI on iPhone 6 plus would look exactly like the one on iPhone 5 but just larger.

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

What is the best practice add video background view?

I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

Twilio Client Python not Working in IOS Browser

I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

MFMessageComposeViewControllerDelegate not being called

I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

How to draw each a vertex of a mesh as a circle

How to draw each a vertex of a mesh as a circle?

NSString to NSDate doesn't work

now it works with this code: NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSDate *date = [dateFormatter dateFromString:myDate]; [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; NSString *dateString = [dateFormatter stringFromDate:date]; cell.timeLabel.text = dateString; ...

Set color CFAttributedStringRef

I have this methods for draw a table ant populated . What i want is to change the color for one word from each column , but i dont know how can i do it . Can somebeday help me ,please ? Any help will be appreciate . in my...

iOS 8 Swift CS193P Calculator Bug Switch Operation

I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

Do I have to use both of these methods?

When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

Override UITabBarController Icon Selection

I'm using a standard UITabBarController with icons at the bottom, each bringing to it's ownViewController. My question is basically: Is there a way to override what happens when an icon is selected rather then directly bringing them to the view? Reason being is because I'm adding a login screen to...

UITabBarViewController doesn't rotate - iOS

I have a UITabBarViewController that contains 5 tabs and a login view which is not part of my tab bar, in my settings I have set that I support all device orientations. but when I run my app, only my login view is the only which rotates. I have created...

Is it possible to obtain an unique iCloud user ID on cocoa?

My iOS app is currently on beta in TestFlight, and as a way to retribute to the nice people who helped me test it I would like to offer them some goodies such as, for instance, the full final version of the app for free. For this, I was thinking...

Adding Image And title both to UIsegmentControl IOS

Is there a way so that you can set both image and title of UISegmentControl simultaneously, so that image appear next to the title , just like image appear next to title in UIButton. I am trying but if I set image of Selected segment of UISegmentControl then title disappears...

App crashes when i start typing in uiseachbar in uitableview

I am making a project in which i am fetching addressbook in my tableview with the help of NSObject class. Now , I allocated a UISearchbar in it , but when i start typing , the app crashes with the following error :---- 'Can't use in/contains operator with collection (not...