drruhc4944 2016-08-31 03:34
浏览 103
已采纳

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

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.

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)

}
  • 写回答

1条回答 默认 最新

  • dongnan1989 2016-08-31 04:35
    关注

    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. There might be an issue in either your construction of a url NSURL(strUrl)! or when calling the NSData(...) constructor and unwrapping its result with !.

    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). We then unwrap the NSData object and then coalesce the strResult when printing it (as its also an optional).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 征集Python提取PDF文字属性的代码
  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?
  • ¥15 Arduino的wifi连接,如何关闭低功耗模式?
  • ¥15 Android studio 无法定位adb是什么问题?