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()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式