使用 NSURLSession 发送 POST 请求

Posted

技术标签:

【中文标题】使用 NSURLSession 发送 POST 请求【英文标题】:Send POST request using NSURLSession 【发布时间】:2013-10-06 14:59:53 【问题描述】:

更新:找到解决方案。可以在文末阅读。

我正在尝试使用NSURLSession 对远程 REST API 执行 POST 请求。这个想法是使用两个参数发出请求:deviceIdtextContent

问题是服务器无法识别这些参数。服务器部分工作正常,因为我已经使用 POSTMAN for Google Chrome 发送了一个 POST 并且它工作得很好。

这是我现在使用的代码:

NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"];
NSString *textContent = @"New note";
NSString *noteDataString = [NSString stringWithFormat:@"deviceId=%@&textContent=%@", deviceID, textContent];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @
                                               @"api-key"       : @"API_KEY",
                                               @"Content-Type"  : @"application/json"
                                               ;
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [NSURL URLWithString:@"http://url_to_manage_post_requests"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    // The server answers with an error because it doesn't receive the params
];
[postDataTask resume];

我用NSURLSessionUploadTask 尝试了相同的过程:

// ...
NSURL *url = [NSURL URLWithString:@"http://url_to_manage_post_requests"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:[noteDataString dataUsingEncoding:NSUTF8StringEncoding] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    // The server answers with an error because it doesn't receive the params
];
[uploadTask resume];

有什么想法吗?

解决方案

我的方法的问题是我在所有请求中都发送了不正确的 Content-Type 标头。因此,代码正常工作所需的唯一更改是删除Content-Type = application/json HTTP 标头。所以正确的代码是这样的:

NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"];
NSString *textContent = @"New note";
NSString *noteDataString = [NSString stringWithFormat:@"deviceId=%@&textContent=%@", deviceID, textContent];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @
                                               @"api-key"       : @"API_KEY"
                                               ;
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [NSURL URLWithString:@"http://url_to_manage_post_requests"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    // The server answers with an error because it doesn't receive the params
];
[postDataTask resume];

与其他参数一起发送图像

如果您需要使用NSURLSession 发布图像以及其他参数,这里有一个示例:

NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"];
NSString *textContent = @"This is a new note";

// Build the request body
NSString *boundary = @"SportuondoFormBoundary";
NSMutableData *body = [NSMutableData data];
// Body part for "deviceId" parameter. This is a string.
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"deviceId"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", deviceID] dataUsingEncoding:NSUTF8StringEncoding]];
// Body part for "textContent" parameter. This is a string.
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"textContent"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", textContent] dataUsingEncoding:NSUTF8StringEncoding]];
// Body part for the attachament. This is an image.
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"ranking"], 0.6);
if (imageData) 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"image"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// Setup the session
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @
                                               @"api-key"       : @"55e76dc4bbae25b066cb",
                                               @"Accept"        : @"application/json",
                                               @"Content-Type"  : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
                                               ;

// Create the session
// We can use the delegate to track upload progress
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

// Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background
NSURL *url = [NSURL URLWithString:@"URL_TO_UPLOAD_TO"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = body;
NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    // Process the response
];
[uploadTask resume];

【问题讨论】:

切线,如果您只使用NSURLSessionUploadTask,它会将原始数据发布到您的服务器。你仍然可以使用它——例如,通过file_get_contents('php://input') in PHP——但你必须在标题中包含其他数据。 不错的解决方案!用它来创建我自己的多部分表单作曲家。 我有一个不同的问题,但关于Content-Type 的提示是我需要弄清楚的所有事情。谢谢! 应该添加问题中的“解决方案”作为答案:) 如果您有一个帖子作为答案而不是将其放在那里,请不要回答您的问题。请参考 Meta 上的这个post 【参考方案1】:

您可以尝试使用 NSDictionary 作为参数。以下将正确地将参数发送到 JSON 服务器。

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST ios", @"name",
                     @"IOS TYPE", @"typemap",
                     nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 

];

[postDataTask resume];

希望这会有所帮助(我正在尝试使用上述方法对 CSRF 真实性问题进行排序 - 但它确实会在 NSDictionary 中发送参数)。

【讨论】:

效果很好!谢谢@greentor!知道如何将图像与“普通”数据一起上传吗? 我已经找到了我的第一个问题的解决方案(无需与NSJSONSerialization 混淆),并且我已经添加了发布图像的代码以及其他参数。我已经更新了原来的帖子。谢谢你的帮助:-) 非常感谢 greentor,我从很久以前就找到了解决方案。你的帖子帮助我解决了我在 ios 7 中使用 Post call to rest service 的所有问题 @sendoa ,如果您知道如何上传图像以及“普通”数据?我急需解决方案。非常感谢提前 @GaganJoshi 阅读了我最初帖子的“发送图像以及其他参数”部分 :-)【参考方案2】:

动机

当你想将 httpBodyDictionary 序列化到Data 时,有时我会遇到一些错误,这在大多数情况下是由于编码错误或由于非@ 而导致的数据格式错误Dictionary中的987654321@符合对象。

解决方案

根据您的要求,一种简单的解决方案是创建 String 而不是 Dictionary 并将其转换为 Data。您在Objective-CSwift 3.0 上编写了以下代码示例。

目标-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&email=example@example.com&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    // Handle your response here
];

// Fire the request
[dataTask resume];

斯威夫特

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&email=example@example.com&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest)  (data, response, error) in
    // Handle your response here


// Fire the request
dataTask.resume()

【讨论】:

NSURLSessionDataTask 行在 urlRequest 之前缺少一个冒号。 谢谢。很干净的答案。为什么该请求应该是可变的?什么可能变异?或者是因为你不断地附加(比如数组或字典)url,然后是method,然后是body,所以它必须是可变的?如果是这种情况,那么哪里需要使用NSURLRequest 嘿 +1 解释一下你能告诉我如何将图像发送到服务器我所知道的只是 api 和密钥“图像”请帮助我很多教程但没有任何解释任何帮助将不胜感激:( @Kuldeep1007tanwar 嗯,这真的取决于你的服务器,你可以尝试通过一个名为 PostMan 的工具来完成,当你最终看到你需要如何发送图像时,我可以帮助你 :) 它是一个 php 服务器,您有任何与 Postman 相关的参考资料吗?【参考方案3】:

您可以使用https://github.com/mxcl/OMGHTTPURLRQ

id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];

NSURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];

id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];

[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];

【讨论】:

感谢您的链接。我不确定我是否理解关于这不是“清晰编码”的抱怨。如果您曾经不得不使用 NSURLSession 创建自己的多部分表单数据,您就会知道这可以为您节省大量的编码。在上面@mxcl 的示例中,创建请求只需要两行。要自己实现这一点,至少需要 12 行代码。 我刚刚意识到他们是如何设法构建多部分请求的。他们抓取要上传的文件并将其保存在其他文件中,其中也包含请求的正文。然后他们可以使用uploadTaskWithRequest:fromFile:。由于您不能使用任何 NSData 方法在后台上传,因此他们修改了实际文件。好点子。 backgroundSessionConfiguration 不允许自定义正文。您在请求对象的正文中放入的任何内容都会被忽略。【参考方案4】:

Swift 2.0 解决方案来了:

 let urlStr = “http://url_to_manage_post_requests” 
 let url = NSURL(string: urlStr) 
 let request: NSMutableURLRequest =
 NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST"
 request.setValue(“application/json” forHTTPHeaderField:”Content-Type”)
 request.timeoutInterval = 60.0 
 //additional headers
 request.setValue(“deviceIDValue”, forHTTPHeaderField:”DeviceId”)

 let bodyStr = “string or data to add to body of request” 
 let bodyData = bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
 request.HTTPBody = bodyData

 let session = NSURLSession.sharedSession()

 let task = session.dataTaskWithRequest(request)
             (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

             if let httpResponse = response as? NSHTTPURLResponse 
                print("responseCode \(httpResponse.statusCode)")
             

            if error != nil 

                 // You can handle error response here
                 print("\(error)")
             else 
                  //Converting response to collection formate (array or dictionary)
                 do
                     let jsonResult: AnyObject = (try NSJSONSerialization.JSONObjectWithData(data!, options:
 NSJSONReadingOptions.MutableContainers))

                     //success code
                 catch
                     //failure code
                 
             
         

   task.resume()

【讨论】:

【参考方案5】:

如果您使用的是 Swift,Just 库会为您执行此操作。它的自述文件示例:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
)  (r)
    if (r.ok)  /* success! */ 

【讨论】:

有趣,非常简单直接=D 我喜欢简单的图案【参考方案6】:

Teja Kumar Bethina 为 Swift 3 更改了代码:

    let urlStr = "http://url_to_manage_post_requests"
    let url = URL(string: urlStr)

    var request: URLRequest = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue("application/json", forHTTPHeaderField:"Content-Type")
    request.timeoutInterval = 60.0

    //additional headers
    request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")

    let bodyStr = "string or data to add to body of request"
    let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) 
        (data: Data?, response: URLResponse?, error: Error?) -> Void in

        if let httpResponse = response as? HTTPURLResponse 
            print("responseCode \(httpResponse.statusCode)")
        

        if error != nil 

            // You can handle error response here
            print("\(error)")
         else 
            //Converting response to collection formate (array or dictionary)
            do 
                let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
                    JSONSerialization.ReadingOptions.mutableContainers))

                //success code
             catch 
                //failure code
            
        
    

    task.resume()

【讨论】:

【参考方案7】:
    use like this.....

    Create file

    #import <Foundation/Foundation.h>`    
    #import "SharedManager.h"
    #import "Constant.h"
    #import "UserDetails.h"

    @interface APISession : NSURLSession<NSURLSessionDelegate>
    @property (nonatomic, retain) NSMutableData *responseData;
    +(void)postRequetsWithParam:(NSMutableDictionary* )objDic withAPIName:(NSString* 
    )strAPIURL completionHandler:(void (^)(id result, BOOL status))completionHandler;
    @end

****************.m*************************
    #import "APISession.h"
    #import <UIKit/UIKit.h>
    @implementation APISession

    +(void)postRequetsWithParam:(NSMutableDictionary *)objDic withAPIName:(NSString 
    *)strAPIURL completionHandler:(void (^)(id, BOOL))completionHandler
    
    NSURL *url=[NSURL URLWithString:strAPIURL];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSError *err = nil;

    NSData *data=[NSJSONSerialization dataWithJSONObject:objDic options:NSJSONWritingPrettyPrinted error:&err];
    [request setHTTPBody:data];

    NSString *strJsonFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"API URL: %@ \t  Api Request Parameter ::::::::::::::%@",url,strJsonFormat);
    //    NSLog(@"Request data===%@",objDic);
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    //  NSURLSession *session=[NSURLSession sharedSession];

    NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                            
                                if (error==nil) 
                                    NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];\
                                    NSLog(@"Response Data=============%@",dicData);
                                    if([[dicData valueForKey:@"tokenExpired"]integerValue] == 1)
                                    

                                        NSLog(@"hello");
                                        NSDictionary *dict = [NSDictionary dictionaryWithObject:@"Access Token Expire." forKey:@"message"];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"UserLogOut" object:self userInfo:dict];
                                    
                                    dispatch_async(dispatch_get_main_queue(), ^
                                        completionHandler(dicData,(error == nil));
                                    );
                                    NSLog(@"%@",dicData);
                                
                                else
                                    dispatch_async(dispatch_get_main_queue(), ^
                                        completionHandler(error.localizedDescription,NO);
                                    );
                                
                            ];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
    [task resume];
    //    );
    
    @end

    *****************************in .your view controller***********
    #import "file"
    txtEmail.text = [txtEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    
            [SVProgressHUD showWithStatus:@"Loading..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];

            NSMutableDictionary *objLoginDic=[[NSMutableDictionary alloc] init];
            [objLoginDic setValue:txtEmail.text forKey:@"email"];
            [objLoginDic setValue:@0            forKey:kDeviceType];
            [objLoginDic setValue:txtPassword.text forKey:kPassword];
            [objLoginDic setValue:@"376545432"  forKey:kDeviceTokan];
            [objLoginDic setValue:@""           forKey:kcountryId];
            [objLoginDic setValue:@""           forKey:kfbAccessToken];
            [objLoginDic setValue:@0            forKey:kloginType];

            [APISession postRequetsWithParam:objLoginDic withAPIName:KLOGIN_URL completionHandler:^(id result, BOOL status) 

                [SVProgressHUD dismiss];

                NSInteger statusResponse=[[result valueForKey:kStatus] integerValue];
                NSString *strMessage=[result valueForKey:KMessage];
                if (status) 
                    if (statusResponse == 1)
                
                        UserDetails *objLoginUserDetail=[[UserDetails alloc] 
                        initWithObject:[result valueForKey:@"userDetails"]];
                          [[NSUserDefaults standardUserDefaults] 
                        setObject:@(objLoginUserDetail.userId) forKey:@"user_id"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self clearTextfeilds];
                        HomeScreen *obj=[Kiran_Storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];
                        [self.navigationController pushViewController:obj animated:YES];
                    
                    else
                        [strMessage showAsAlert:self];
                    
                
            ];
        
**********use model class for represnt data*************

    #import <Foundation/Foundation.h>
    #import "Constant.h"
    #import <objc/runtime.h>


    @interface UserDetails : NSObject
    @property(strong,nonatomic) NSString *emailId,
    *deviceToken,
    *countryId,
    *fbAccessToken,
    *accessToken,
    *countryName,
    *isProfileSetup,
    *profilePic,
    *firstName,
    *lastName,
    *password;

    @property (assign) NSInteger userId,deviceType,loginType;

    -(id)initWithObject :(NSDictionary *)dicUserData;
    -(void)saveLoginUserDetail;
    +(UserDetails *)getLoginUserDetail;
    -(UserDetails *)getEmptyModel;
    - (NSArray *)allPropertyNames;
    -(void)printDescription;
       -(NSMutableDictionary *)getDictionary;

    @end

    ******************model.m*************

    #import "UserDetails.h"
    #import "SharedManager.h"

    @implementation UserDetails



      -(id)initWithObject :(NSDictionary *)dicUserData
       
       self = [[UserDetails alloc] init];
       if (self)
       
           @try 
               [self setFirstName:([dicUserData valueForKey:@"firstName"] != [NSNull null])? 
               [dicUserData valueForKey:@"firstName"]:@""];


               [self setUserId:([dicUserData valueForKey:kUserId] != [NSNull null])? 
               [[dicUserData valueForKey:kUserId] integerValue]:0];


               
        @catch (NSException *exception) 
            NSLog(@"Exception: %@",exception.description);
        
        @finally 
        
    
    return self;


    -(UserDetails *)getEmptyModel
    [self setFirstName:@""];
    [self setLastName:@""];



    [self setDeviceType:0];


    return self;
       

     -  (void)encodeWithCoder:(NSCoder *)encoder 
    //    Encode properties, other class variables, etc
    [encoder encodeObject:_firstName forKey:kFirstName];


    [encoder encodeObject:[NSNumber numberWithInteger:_deviceType] forKey:kDeviceType];

    

    - (id)initWithCoder:(NSCoder *)decoder 
    if((self = [super init])) 
        _firstName = [decoder decodeObjectForKey:kEmailId];

        _deviceType= [[decoder decodeObjectForKey:kDeviceType] integerValue];

    
    return self;
    
    - (NSArray *)allPropertyNames
    
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;
    for (i = 0; i < count; i++)
    
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    

    free(properties);

    return rv; 
     

    -(void)printDescription
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

    for(NSString *key in [self allPropertyNames])
    
        [dic setValue:[self valueForKey:key] forKey:key];
    
    NSLog(@"\n========================= User Detail ==============================\n");
    NSLog(@"%@",[dic description]);
    NSLog(@"\n=============================================================\n");
    
    -(NSMutableDictionary *)getDictionary
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    for(NSString *key in [self allPropertyNames])
    
        [dic setValue:[self valueForKey:key] forKey:key];
    
    return dic;
    
    #pragma mark
    #pragma mark - Save and get User details
    -(void)saveLoginUserDetail
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
    [Shared_UserDefault setObject:encodedObject forKey:kUserDefault_SavedUserDetail];
    [Shared_UserDefault synchronize];
    
      +(UserDetails *)getLoginUserDetail
      NSData *encodedObject = [Shared_UserDefault objectForKey:kUserDefault_SavedUserDetail];
    UserDetails *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
   
    @end


     ************************usefull code while add data into model and get data********

                   NSLog(@"Response %@",result);
                  NSString *strMessg = [result objectForKey:kMessage];
                 NSString *status = [NSString stringWithFormat:@"%@",[result 
                objectForKey:kStatus]];

            if([status isEqualToString:@"1"])
            
                arryBankList =[[NSMutableArray alloc]init];

                NSMutableArray *arrEvents=[result valueForKey:kbankList];
                ShareOBJ.isDefaultBank = [result valueForKey:kisDefaultBank];
                if ([arrEvents count]>0)
                

                for (NSMutableArray *dic in arrEvents)
                    
                        BankList *objBankListDetail =[[BankList alloc]initWithObject:[dic 
                         mutableCopy]];
                        [arryBankList addObject:objBankListDetail];
                    
           //display data using model...
           BankList *objBankListing  =[arryBankList objectAtIndex:indexPath.row];

【讨论】:

不要使用-[NSUserDefaults synchronize]。来自Apple's documentation“这个方法是不必要的,不应该使用。”

以上是关于使用 NSURLSession 发送 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发网络篇—发送GET和POST请求(使用NSURLSession)

iOS开发网络篇—发送GET和POST请求(使用NSURLSession)

使用 NSURLSession 发送 POST 请求

网络编程 利用NSURLSession发送GET POST请求

NSURLSession 发送 GET 请求,即使我在 HTTPMethod 中设置了 POST

如何在 Swift 中发出 NSURLSession POST 请求