2015-09-06 32 views
2

我已经从API解析了我的数据,但是当我尝试从解析的NSDictionary数据中设置一些值时,println语句不会被调用。它发生在字典中用“用户”键,我尝试设置学生的名字和姓氏。JSON解析的数据没有被调用? Swift

func getUserData(hostViewController: UIViewController) { 
     if self.userID == nil{ 
      println("User ID is nil") 
     } 
     else { 
     var key = self.userID 
     let urlString = UdacityClient.Constants.BaseURLSecure + "/users" + "/\(key)" 
     println(urlString) 
     let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!) 
     let request = NSMutableURLRequest(URL: url!) 


     let task = session.dataTaskWithRequest(request) {data, response, error in 
      if error != nil { 
       dispatch_async(dispatch_get_main_queue(), {() -> Void in 
        println(error) 
        let alertController = UIAlertController(title: "Oh no", message: "Error in User Data", preferredStyle: UIAlertControllerStyle.Alert) 

        let cancelAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in 
         hostViewController.dismissViewControllerAnimated(true, completion: nil) 
        }) 
        alertController.addAction(cancelAction) 

        hostViewController.presentViewController(alertController, animated: true, completion: nil) 
       }) 

       println("Error in User Data") 

      } else { 
       let newData = data.subdataWithRange(NSMakeRange(5, data.length - 5)) 
       var parsingError: NSError? = nil 
       let parsedResult = NSJSONSerialization.JSONObjectWithData(newData, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as! NSDictionary 


       if let userDictionary = parsedResult["user"] as? [String: AnyObject] { 
        if let firstName = userDictionary["first_name"] as? String { 
         self.firstName = firstName 
         println("This is not printing ") 
         println(firstName) 
        } 
       } 

       if let userDictionary = parsedResult["user"] as? [String: AnyObject] { 
        if let lastName = userDictionary["last_name"] as? String { 
         self.lastName = lastName 
         println("This is not printing also") 
         println(lastName) 
        } 
       } 

       if let err = parsingError { 
        dispatch_async(dispatch_get_main_queue(),{() -> Void in 
         println(err) 
         let alertController = UIAlertController(title: "Oh no", message: "Error in Parsing User Data from Udacity", preferredStyle: UIAlertControllerStyle.Alert) 

         let cancelAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in 
          hostViewController.dismissViewControllerAnimated(true, completion: nil) 
         }) 
         alertController.addAction(cancelAction) 

         hostViewController.presentViewController(alertController, animated: true, completion: nil) 
        }) 

       } 


      } 
      } 


     task.resume() 
     } 
    } 

我的请求URL:

https://www.udacity.com/api/users/Optional("3778758647") 

我ResponseKeys结构

struct JSONResponseKeys { 
     //getSessionID 
     static let Status = "status" 
     static let Account = "account" 
     static let Key = "key" 
     static let Session = "session" 
     static let ID = "id" 

     //getUserData 
     static let User = "user" 
     static let FirstName = "first_name" 
     static let LastName = "last_name" 


    } 

致命错误而展开的可选值发生在我称为第一姓名和我的客户的学生姓名如下:

UdacityClient.sharedInstance().firstName!) and  UdacityClient.sharedInstance().lastName! 

JSON解析结果控制台日志

{ 
    error = "Parameter 'user_key' key contains unescaped special character '\"': 'Optional(\"3778758647\")'"; 
    parameter = "user_key"; 
    status = 400; 
} 
+0

log parsedResult并显示结果。 – Shoaib

+0

您是否尝试过'userDictionary [“first_name”]作为AnyObject!如?字符串' –

+0

@Shoaib完成。请参阅更新后的问题。 –

回答

2

我看起来像你的主要错误是由于userID是一个需要展开的可选值。这就是为什么你看到

https://www.udacity.com/api/users/Optional("3778758647") 而不是 https://www.udacity.com/api/users/3778758647和你的服务器错误说同样的事情。

试试这个基本轮廓,而不是:

if self.userID == nil { 
    ... 
} 

你可以使用保护语句提前返回,就像这样:

guard let userID = self.userID as? String else { return } 

这个也有展开你的价值利益,得到摆脱"Optional()"

另一种方式将使用:

if let userID = self.userID as? String { 
    ... 
} 
0

首先,我建议你使用SwiftyJson数据解析(虽然我们是在它,你可以使用Alamofire甚至afnetworking为REST调用)。

我给你几个例子,用Swify解析数据有多简单。

这是一个对象

public class MyObject: NSObject, JsonInitializableProtocol { 
var name = "" 
var value = "" 
var count = 0 

required public init(json:JSON) { 
    name = json["Name"].stringValue ?? "" 
    value = json["Value"].stringValue ?? "" 
    count = json["Count"].intValue ?? 0 
} 

override init() {} 
} 

而一个FUNC是GET与AFNetworking NSData的,将其转换成JSON并创建和类型MyObject来的对象模型,并通过completionBlock其传递回

func getObjWithUrl(url: String, completionHandler: (object: MyObject?, error: NSError?) -> Void) { 
     manager.GET(url, parameters: nil, success: { (operation: AFHTTPRequestOperation!, data: AnyObject?) -> Void in 
       let json = JSON(data : data as! NSData) 
       let myObject = MyObject(json: json) 
       completionHandler(myObject, nil) 
      }, failure: { (operation: AFHTTPRequestOperation!, error: AnyObject?) -> Void in 
       if let operationUnwrapped = operation as AFHTTPRequestOperation? { 
        var error = NSError(operation: operationUnwrapped, message: nil) 
        completionHandler(nil, wsError) 
       } 
      } 
    } 
+0

感谢您的建议,但您可以通过更具体地回答我的问题来提供更多帮助。 –