【问题标题】:How can i fix "Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}"如何修复“错误域 = NSCocoaErrorDomain 代码 = 3840”无价值。“UserInfo = {NSDebugDescription = 无价值。}”
【发布时间】:2016-08-20 22:40:00
【问题描述】:

当我运行我的代码时,我得到了这个错误,我不知道为什么。

错误域=NSCocoaErrorDomain 代码=3840“无价值。” UserInfo={NSDebugDescription=无值。}

我在互联网上寻找它,但我没有找到任何东西。

这是我的代码:

 let myUrl = NSURL(string: "http://foodhelper.club/registerUser.php");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";

    let postString = "userEmail=\(userEmail!)&userFirstName=\(userFirstName!)&userLastName=\(userLastName!)&userPassword=\(userPassword!)";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        dispatch_async(dispatch_get_main_queue())
        {



            if error != nil {
                self.alertMessage(error!.localizedDescription)
                print("fail")
                return
            }

            do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
                print ("1")
              if let parseJSON = json {

                    let userId = parseJSON["userId"] as? String
                    print ("2")
                    if( userId != nil)
                    {
                        let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.Alert);

                        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in

                            self.navigationController?.popViewControllerAnimated(true)                            }

                        myAlert.addAction(okAction);
                        self.presentViewController(myAlert, animated: true, completion: nil)
                    } else {
                        let errorMessage = parseJSON["message"] as? String
                        print ("3")
                        if(errorMessage != nil)
                        {
                            self.alertMessage(errorMessage!)
                        }

                    }

                }
            } catch{

                //email vergleich fehlt, egal ob
                print(error)
                print("catched error")

                let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.Alert);

                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in


                    self.navigationController?.popViewControllerAnimated(true)
                }

                myAlert.addAction(okAction);
                self.presentViewController(myAlert, animated: true, completion: nil)


            }



        }

    }).resume()


}

感谢您的帮助

【问题讨论】:

  • 这不是和this一样吗?
  • 不,这是一个普遍的问题,并不像我的其他问题那样具体,所以我希望我能在这里得到答复。 @OOPer
  • 那么你认为你的另一个问题应该是什么?您认为这两个问题都需要作为独立问题存在?
  • 但现在我得到了答案,所以对我来说没问题:)
  • 好的,那么,请努力为您的第一个问题找到答案。

标签: json database swift http


【解决方案1】:

您需要设置 content-type 标头值以使用 JSON。

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

将代码更新为 Swift 3 并删除了与请求无关的所有内容:

let myUrl = URL(string: "http://foodhelper.club/registerUser.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let postString = "userEmail=email&userFirstName=firstname&userLastName=lastname&userPassword=password";
request.httpBody = postString.data(using: String.Encoding.utf8);

URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
        if error != nil {
            print("fail")
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
            print ("1")

            if let parseJSON = json {

                let userId = parseJSON["userId"] as? String
                print ("2")
                if( userId != nil) {

                } else {
                    let errorMessage = parseJSON["message"] as? String
                    print ("3")
                }
            }
        } catch{
            print(error)
        }
}).resume()

【讨论】:

  • 谢谢你,这帮助我解决了这个问题:)
【解决方案2】:

我刚刚遇到同样的错误,在我的情况下,这发生在 Swift(toJson 方法)中,同时将 empty Data(不是 NSData)转换为 Json。

解决方法,先检查Data是否为空,如:

public typealias JsonValue = AnyHashable;
public typealias Json = [String: JsonValue];

extension Data {
    public func toJson() throws -> Json {
        if self.isEmpty {
            return Json();
        }
        return try JSONSerialization.jsonObject(with: self, options: [])
            as? Json ?? Json();
    }

    public static func fromJson(_ data: Json) throws -> Data {
        return try JSONSerialization.data(withJSONObject: data);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2018-02-20
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多