美文网首页
Swift_网络请求

Swift_网络请求

作者: _杜兜兜_ | 来源:发表于2016-10-10 10:38 被阅读62次

    一 第一种:导入第三方

    import Alamofire//网络请求
    import SwiftyJSON//数据解析
    

    1,参数为value

    let dic = []
    Alamofire.request(.POST,"", parameters:dic)
    .responseJSON {response in
        if let Error = response.result.error{
            print(Error,"")
        }else if let value = response.result.value{
            let json = JSON(value)
            print(json)
        }
    }
    

    2,参数为body

    let dic = []
    Alamofire.request(.POST,"", parameters:dic, encoding: .JSON)
    .responseJSON {response in
        if let Error = response.result.error{
            print(Error,"")
        }else if let value = response.result.value{
            let json = JSON(value)
            print(json)
        }
    }
    

    二 第二种:不需要导入第三方

        let parameter = []
        do {
            let body = try! NSJSONSerialization.dataWithJSONObject(parameter, options: NSJSONWritingOptions.PrettyPrinted)
            let request = NSMutableURLRequest(URL: NSURL(string: "")!)
            request.HTTPBody = body
            request.HTTPMethod = "POST"
            //设置json格式
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
                let value : AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.AllowFragments)
                print(value)
    //            let json = JSON(value)
    //            print(json)
            }
            task.resume()
        }
    

    相关文章

      网友评论

          本文标题:Swift_网络请求

          本文链接:https://www.haomeiwen.com/subject/xdwmyttx.html