快速发布数据并从 json url 获取数据?

Posted

技术标签:

【中文标题】快速发布数据并从 json url 获取数据?【英文标题】:post data and get data from json url in swift? 【发布时间】:2017-02-09 06:46:05 【问题描述】:

我尝试了下面的代码来发布并从 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】:

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)
    
    


输出:-

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

【讨论】:

我在视图控制器中编写了按钮以及如何在 swift 代码中在 appdelegate 中隐藏该按钮? 我不知道你为什么需要这个,但你必须为UIButton创建一个带有状态(BOOL or ENUM)的function,这是你想隐藏和显示在你的ViewController Class中然后用NotificationCenter.defaultAppDelegate调用函数,或者可以使用Protocol(delegate methods)进行隐藏/显示。

以上是关于快速发布数据并从 json url 获取数据?的主要内容,如果未能解决你的问题,请参考以下文章

在 UISegment 之间快速切换时应用程序崩溃

从 URL 中获取 ID 并从数据库中选择它

将一些数据传递到 iTunes Store url 并从应用程序中获取

Django 应用程序视图 - 如何从 url 中的 django 数据库中获取条目并从数据库中获取更多视图信息?

如何从 JsonArray 中获取 NSDictonarys?

如何获取 iframe 的当前位置?