IOS 使用 POST、GET 提交 JSON 数据到服务器

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了IOS 使用 POST、GET 提交 JSON 数据到服务器脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

最近被安排了一项在 IOS 下 POS T数据的任务,在 GOOGLE 的帮助下总算是做出来了。网上的教程不全、乱、缺少一个全方位适合初级开发者的教程。

阅读本教程你需要:

  • 引用开库 ASIHTTPRequest(负责网络通信)、JSONKIT(负责封装和解析JSON数据)
  • 管理开源库则需要工具 cocoapods(配置 ruby 和 gem),这是安装教程

好的,现在假设里上述工具都已经配置好了

  • 新建一个工程,我以 Demo 为例 /Users/Demo
  • 在命令终端中进入 Demo 目录
  • 用 vim 命令新建一个文件 PoDFile

    输入命令 vim Podfile

    按下 i 键,进入输入模式
    内容为:

        platform :ios
        pod 'ASIHTTPRequest'
    

    按下 esc 进入命令模式,连按两次大写的 Z 保存并退出 vim

  • 输入命令 pod install 等待 出现

    [!] From now on use Demo.xcworkspace.

    finder 中打开 xcworkspace 来开启工程(进行此操作最好先把 xcode 关闭,不然会看到“xxx 已经在xcode中打开的提示”)

  • 把 github 上的 JSONKit 搞下来

    git clone https://github.COM/johnezang/JSONKit.git
    
  • 导入头文件

    #import "JSONKit.h"
    #import <ASIHTTPRequest/ASIHTTPRequest.h>

在这里需要处理两个 bug

  • JSONKit 不支持 arc 模式,所以在 Build Phases 中把 JSONKit.m Compiler Flags 填入“-fno-objc-arc”
  • 不支持古老的 isa,所以你要这样做

    Include <objc/runtime.h>.

    Replace everything like array->isa =_JKArrayClass; with object_setClass(array, _JKArrayClass)

    And everything like class = array.isa with class = object_getClass(array)

好的,现在开始写代码了

假设我们要上传的 JSON 格式是这样的:

   {"email":"chenyu380@gmail.com","password":"FxxkYourAss"}

一个登录方法

  -(NSDictionary*)Login:(NSString *)email password:(NSString *)password
  {
  NSMutableDictionary *resultsDictionary;// 返回的 JSON 数据
  NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:password, @"password",email,@"email",nil];
  if ([NSJSONSerialization isValidJSONObject:userDictionary])
  {

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &amp;error];
    NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
    NSURL *url = [NSURL URLWithString:@"http://seanchense.com/LOGin"];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request addRequestHeader:@"Content-tyPE" value:@"application/json; charset=utf-8"];
    [request addRequestHeader:@"Accept" value:@"application/json"];

    [request setRequestMethod:@"POST"];
    [request setPostBody:tempJsonData];
    [request startSynchronous];
    NSError *error1 = [request error];
    if (!error1)
    {
        NSString *response = [request responseString];
        NSLog(@"test:%@",response);
        NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];

    }
  }

  return resultsDictionary;
  }

好的现在完成了

脚本宝典总结

以上是脚本宝典为你收集整理的IOS 使用 POST、GET 提交 JSON 数据到服务器全部内容,希望文章能够帮你解决IOS 使用 POST、GET 提交 JSON 数据到服务器所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。