Detailed explanation of uploading files with application / JSON in IOS development

Time:2022-4-25

This article will explain to you the form of uploading files in application / JSON in IOS through example code. For details, please refer to this article.

In the process of background interaction with sever, sometimes they need us IOS developers to upload in the form of “application / JSON”.

NSString *accessUrl = [NSString stringWithFormat:@"%@/xxx",@"https://www.xxxxx.com:xxxx"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:accessUrl]];
 request.HTTPMethod = @"POST";
 //Set request header
 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 //Set request body
 NSMutableData *body = [NSMutableData data];
 [body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
 [request setHTTPBody:body];
 NSHTTPURLResponse* urlResponse = nil;
 NSError *error = [[NSError alloc] init];
 NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
 NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
 if (result == nil) {
  Nslog (@ "JSON parsing failed!");
 }
 else
 {
  NSData *jsonData = [result dataUsingEncoding:NSUTF8StringEncoding];
  NSError *err;
  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
               options:NSJSONReadingMutableContainers
                error:&err];
  if(err) {
   Nslog (@ "JSON parsing failed:% @", ERR);
  }
  success(dic);
 }

summary

The above is a detailed explanation of the example of uploading files with application / JSON in IOS development introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!