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

我试图通过PHP获取PHP脚本的HTML来通过PHP连接到MySQL数据库。 我计划使用URL将变量(如用户名,密码或id)传递给PHP脚本,然后调用MySQL。 但是,每当我尝试使用 NSURL </ code>获取网页的响应时,都会发生错误。 这是我正在使用的代码:</ p>

  let myUrl = NSURL(string:“http://www.google.com”)
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod =“POST”
let task = NSURLSession.sharedSession()。dataTaskWithRequest(request){
data,response in error in
let responseString = NSString(data:data!,encoding: NSUTF8StringEncoding)
如果错误!= nil {
print(“错误:\(错误)”)
}
print(“响应:\(响应)”)
print(“响应字符串:\(responseString) )“)
}
task.resume()
</ code> </ pre>

我是否需要格式化网站的输出才能正确传输到Swift? 感谢您的帮助。</ p>
</ div>

展开原文

原文

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个回答



您的代码在Xcode 7.1的游乐场中运行,不会产生任何错误。 为了让异步代码在游乐场中执行,我添加了2行。 亲自尝试一下。 所以我想问题出在你的服务器上。</ p>

  import Foundation 
import XCPlayground

//让异步代码运行
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
\ nlet myUrl = NSURL(字符串:“http://www.google.com”)
let request = NSMutableURLRequest(URL:myUrl!)
request.HTTPMethod =“POST”
let task = NSURLSession.sharedSession()。dataTaskWithRequest( 请求){
数据,响应,错误在
让responseString = NSString(数据:数据!,编码:NSUTF8StringEncoding)
如果错误!= nil {
print(“错误:\(错误)”)
}
print(“响应:\(响应)”)
print(“响应字符串:\(responseString)”)
}
task.resume()
</ code> </ pre>
\ n

如果你无法弄清楚出了什么问题,分享错误信息将有助于其他人了解发生了什么。</ p>

更新:
我在iOS项目中尝试了你的代码代码 崩溃是因为你没有检查数据是否为零并且只是在这一行打开它:</ p>

  let responseString = NSString(data:dat  a!,encoding:NSUTF8StringEncoding)
</ code> </ pre>

但为什么数据结果为零? 这是因为iOS 9中的App Transport Security默认情况下不允许您使用HTTP。 您的服务器必须是TLS v1.2或更高版本的HTTPS。 要允许HTTP请求,请参阅:在iOS 9和OSX 10.11中配置应用程序传输安全性异常 </ p>

此外,您应该在使用数据之前检查错误以避免崩溃。</ p>
\ n

 让myUrl = NSURL(字符串:“http://www.google.com”)
let request = NSMutableURLRequest(URL:myUrl!)
request.HTTPMethod =“POST”
let task = NSURLSession .sharedSession()。dataTaskWithRequest(request){
数据,响应,错误
//在使用数据之前检查错误
如果错误!= nil {
print(“错误:\(错误)”)\ n return
}
让responseString = NSString(data:data!,encoding:NSUTF8StringEncoding)
print(“Response:\(response)”)
print(“Response String:\(responseString)”)
}
task.resume()
</ code> </ pre>
</ div>

展开原文

原文

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

dqyanc7264
dqyanc7264 我已经更新了我的答案。 看看是否能解决您的问题
接近 5 年之前 回复
douzhaochan6468
douzhaochan6468 感谢您的帮助。 这段代码在Playground中运行良好,但是当我尝试使用它时(减去Playground导入和无限执行行),应用程序崩溃了。 我目前在UI按钮上执行此代码,然后将标签更改为“responseString”。 我没有得到任何我能理解的错误消息,应用程序崩溃了。 谢谢您的帮助
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问