duanqian2368 2015-10-27 01:14
浏览 125

如何使用Swift的NSURL格式化HTML,PHP

I am attempting to connect to a MySQL database with Swift through PHP by getting the HTML of a PHP script. I plan on using the URL to pass variables such as username, password, or id to the PHP script then call the MySQL. However, whenever I attempt to get the response of a webpage with NSURL an error occurs. Here is the code I am using:

let myUrl = NSURL(string: "http://www.google.com")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        if error != nil {
            print("Error: \(error)")
        }
        print("Response: \(response)")
        print("Response String: \(responseString)")
    }
    task.resume()

Do I need to format the output from the website to be properly transferred to Swift? Thank you for the help.

  • 写回答

1条回答 默认 最新

  • douzangdang2225 2015-10-27 02:04
    关注

    Your code runs in Xcode 7.1's playground without producing any errors. In order to let asynchronous code execute in playground I added 2 lines. Try it yourself. So I guess the problem lies in your server.

    import Foundation
    import XCPlayground
    
    // Let asynchronous code run
    XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
    
    let myUrl = NSURL(string: "http://www.google.com")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
      data, response, error in
      let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
      if error != nil {
        print("Error: \(error)")
      }
      print("Response: \(response)")
      print("Response String: \(responseString)")
    }
    task.resume()
    

    If you can't figure out what's wrong, sharing the error message will help others find out what's happened.

    UPDATE: I tried your code in a iOS project the code crashes because you are not checking if the data is nil and just unwrapping it at this line:

    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    

    But why the data turns out to be nil? It is because App Transport Security in iOS 9 does not allow you to use HTTP by default. Your server has to be HTTPS with TLS v1.2 or higher. To allow HTTP requests, refer to this: Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11

    Also you should check the error before using the data to avoid crash.

    let myUrl = NSURL(string: "http://www.google.com")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
      data, response, error in
      // Check error before using the data
      if error != nil {
        print("Error: \(error)")
        return
      }
      let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
      print("Response: \(response)")
      print("Response String: \(responseString)")
    }
    task.resume()
    
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?