发布数据并从swson中的json url获取数据?

时间:2017-02-09 06:46:05

标签: ios json post get swift3

我尝试使用以下代码发布并从json获取数据,从json获取数据

http://beta.json-generator.com/api/json/get/EJoC6gB_z

[
  {
    "UserRole": "User",
    "UserName": "Trinadh Reddy",
    "Id": 15,
    "Email": "trinadhvidavaluru@gmail.com"
  },
  {
    "UserRole": "User",
    "UserName": "fayaz sk",
    "Id": 16,
    "Email": "fayaz.net717@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": "Gowtham M",
    "Id": 17,
    "Email": "mgowtham666@gmail.com"
  },
  {
    "UserRole": "User",
    "UserName": "fayaz sk",
    "Id": 18,
    "Email": "fayaz8484@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": null,
    "Id": 19,
    "Email": null
  },
  {
    "UserRole": "User",
    "UserName": null,
    "Id": 20,
    "Email": null
  },
  {
    "UserRole": "NewUser",
    "UserName": "Fayaz Shaik",
    "Id": 21,
    "Email": "fayaz717@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": "Trinadh Reddy",
    "Id": 22,
    "Email": "trinadh.engineer@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": "tarun gandham",
    "Id": 23,
    "Email": "gandham.tarun@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": null,
    "Id": 24,
    "Email": "admin@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": "John",
    "Id": 25,
    "Email": "john@gmail.com"
  },
  {
    "UserRole": "NewUser",
    "UserName": "venkatesh kakumani",
    "Id": 26,
    "Email": "veenkys01@gmail.com"
  }
]

let givenName = user.profile.name     
let email  = user.profile.email

let param=["UserName":givenName!,"Email":email!] as Dictionary<String,String>

let request = NSMutableURLRequest(url: NSURL(string:"http://sstarapiservice.azurewebsites.net/api/users/")! as URL)

let session = URLSession.shared
request.httpMethod = "POST"

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

let task = session.dataTask(with: request as URLRequest) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
    do {
        if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
            print("Response: \(json)")

            if var role = json["UserRole"] as AnyObject? as! String?
            {
                print("assigned Role= \(role)")
                if role == "User"{
                   print("App permissions approved")
                    let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)

                    let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
                    let  pageNav = UINavigationController(rootViewController:page)
                    let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
                    appDelegate.window?.rootViewController=pageNav
                    self.window?.rootViewController=pageNav
                    //self.window?.rootViewController = page
                }

                else{
                    print("wait for Approval...")



                    let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)

                    let page=myStoryBoard.instantiateViewController(withIdentifier: "ApprovalUser") as! HomeViewController
                    let  pageNav = UINavigationController(rootViewController:page)
                    let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
                    appDelegate.window?.rootViewController=pageNav
                    self.window?.rootViewController=pageNav

                   // let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)

                   // let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

                   // let  pageNav = UINavigationController(rootViewController:page)

                  //  let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate


                   // appDelegate.window?.rootViewController=pageNav

                 //   self.window?.rootViewController=pageNav
                    //self.window?.rootViewController = page
                }
            }

            //
        }
        else {
            var jsonStr = " "
            var jsonDictionary = [String: Any]()

            jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String

            print("Error could not parse JSON: \(jsonStr)")
            print("121")

            if var role = jsonStr as String?{
            print("role= \(role)")
            }

            var role = JSONDict["UserRole"] as AnyObject? as! String?
            print("success = \(role)")

      //      if var role = jsonDictionary["UserRole"] as! String?
       //     {
        //        print("role is:\(role)")
          //  }
            let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)

            let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

            let  pageNav = UINavigationController(rootViewController:page)

            let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate


            appDelegate.window?.rootViewController=pageNav

            self.window?.rootViewController=pageNav



        }
    } catch let parseError {
        print(parseError)// Log the error thrown by `JSONObjectWithData`
        let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("Error could not parse JSON: '\(jsonStr)'")
        print("12")
    }
}

task.resume()

1 个答案:

答案 0 :(得分:0)

Swift 3

中从Webservice APi请求JSON数据

我在这里使用AlamofireURLSession添加了两种方法: -

import UIKit
import Alamofire

class ViewController: UIViewController {

    let urlString = "http://beta.json-generator.com/api/json/get/EJoC6gB_z"

    override func viewDidLoad() {
        super.viewDidLoad()

        // Choose only one function here for calling webservice
        getValueofUser()

        //Or

        getuserDetails()
    }

    //MARK: - By Using Alamofire
    func getValueofUser(){

        Alamofire.request(urlString, method: .get)
            .responseJSON { response in
                print("Success: \(response.result.isSuccess)")
                switch response.result {
                case .success:
                    self.successGetTermsData(response: response.result.value! as Any)
                case .failure(let error):
                    print(error)
                }

           }

    }

    //MARK: - Or Use URLSession methods
    func getuserDetails(){
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with:url!) { (data, response, error) in
            if error != nil {
                print(error ?? "")
            } else {
                do {
                    let response = try JSONSerialization.jsonObject(with: data!, options: [])
                    self.successGetTermsData(response: response)
                } catch let error as NSError {
                    print(error)
                }
            }

            }.resume()

    }

    func successGetTermsData(response: Any){
        let arrayOfDetails = response as? [[String: Any]] ?? []

        // Do Something with the Array
        //Here you will be get Array of User Related Details
        let email = arrayOfDetails[0]["Email"] as? String ?? ""
        let username = arrayOfDetails[0]["UserName"] as? String ?? ""
        let Id = arrayOfDetails[0]["Id"] as? Int ?? 0
        let UserRole = arrayOfDetails[0]["UserRole"] as? String ?? ""
        print("Email ID -" ,email, "User Name -", username, "ID -",Id, "UserRole -", UserRole)
    }

}

OutPut: -

Email ID - trinadhvidavaluru@gmail.com User Name - Trinadh Reddy ID - 15 UserRole - User