简体   繁体   English

如何使用php将iOS应用连接到mySQL数据库

[英]How to connect iOS app to mySQL database using php

So this is the piece of code causing a problem. 因此,这是导致问题的代码段。 It gives me a fatal error and says that an optional value is giving nil. 它给了我一个致命错误,并说一个可选值给出了nil。

How do i fix this? 我该如何解决? This only works when I enter the first field only (the name field) and then submit, it pops up on my database. 仅当我仅输入第一个字段(名称字段)然后提交时,此方法才起作用,它会在我的数据库中弹出。 However, when I fill in more than one field, it crashes. 但是,当我填写多个字段时,它崩溃了。

My code: 我的代码:

@IBAction func registerButtonTapped(sender: AnyObject) {

    let strURL: String = "http://www.blabla.com.eg/blabla.php?name=\(nameField.text!)&company=\(companyField.text!)&email=\(emailField.text!)&phonenumber=\(phoneNumberField.text!)"
    let dataURL: NSData = NSData(contentsOfURL: NSURL(string: strURL)!)!
    let strResult: String = String(data: dataURL, encoding: NSUTF8StringEncoding)!
    print("\(strResult)")


    self.dismissViewControllerAnimated(true, completion: nil)

}

Your problem is that one (or more) of your optionals is nil when you try to access it. 您的问题是,当您尝试访问可选选项时,其中一个(或多个)为零。 Its important to understand optionals if you are doing swift development, I'd recommend going through the documentation. 如果您要进行快速开发,了解可选选项很重要,建议您阅读文档。

let dataURL: NSData = NSData(contentsOfURL: NSURL(string: strURL)!)!
let strResult: String = String(data: dataURL, encoding: NSUTF8StringEncoding)!

In the code above, when you use ! 在上面的代码中,当您使用! you are telling swift that you are 100% sure that optional contains a value. 您告诉swift,您100%确信optional包含一个值。 There might be an issue in either your construction of a url NSURL(strUrl)! 网址NSURL(strUrl)!构造都可能有问题NSURL(strUrl)! or when calling the NSData(...) constructor and unwrapping its result with ! 或在调用NSData(...)构造函数并使用!展开其结果时 .

Try something like this: 尝试这样的事情:

if let url = NSURL(string: strURL) {
   if let data = NSData(contentsOfURL: url) {
       var strResult = String(data: data, encoding: NSUTF8StringEncoding)
       print(strResult ?? "Something Went Wrong")
   }
   else { // get rid of this else when you find your issue
       print("Could not instantiate an NSData object out of that url")
   }
}
else {  // get rid of this else when you find your issue
   print("Your URL is nil!, check the strUrl")
}

Here, we first unwrap the NSURL as NSURL(string) constructor returns an optional (the string you pass might be an invalid URL). 在这里,我们首先将NSURL解包,因为NSURL(string)构造函数返回一个可选值(您传递的字符串可能是无效的URL)。 We then unwrap the NSData object and then coalesce the strResult when printing it (as its also an optional). 然后,我们解开NSData对象,然后在打印strResult时合并它(也是可选的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM