开发中,我们接触就多得请求方式是post
和get
,但是有时我们需要用到put
方式,然而早就帮我们封装好了(万幸)。 并且后台需要我们传递JSON格式的数据,这时我们会想那还不简单,把以往的字典转换为JSON不就好了
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];复制代码
然后后台反馈的结果是传递的json格式解析不出来,于是百度之后,发现这样才是正确的写法(以下把AFN二次封装了一遍)
#pragma mark -- PUT请求 --+ (void)putWithURLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [manager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }];}复制代码
这时你会发现还是上传不成功,原因是受到JSON格式的思维误区,以为还要转换为JSON格式,其实是不需要的,直接传递字典形式就可以了 #####下面为调用方法
NSDictionary *parameter = @{@"defeatNote":self.textView.text,@"leadsId":@([self.leadsInfoId integerValue]),@"defeatType":@"7"};[ZYNetWorking putWithURLString:urlString parameters:parameter success:^(id responseObject) { // 如果写这句话 会导致程序崩溃 //id obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",responseObject); } failure:^(NSError *error) { }];复制代码