简体   繁体   English

Xcode 7 Swift 2后台页面加载

[英]Xcode 7 Swift 2 Background page load

I need to be able to click a button so that it will load a webpage. 我需要能够单击一个按钮,以便它将加载网页。 The problem is i don't want it to open the page in safari, but i want the webpage to load in the background so that i can press other buttons to load other pages in the background. 问题是我不希望它在野生动物园中打开页面,但我希望在后台加载网页,以便可以按其他按钮在后台加载其他页面。

REASON: 原因:

I have developed a remote controlled light, operable through the internet or my local ip (192.168.0.3). 我开发了一种可通过互联网或本地IP(192.168.0.3)进行操作的远程控制灯。 The webpage is loaded on the raspberry and if i go on "192.168.0.3/On.php" the light turns on. 该网页已加载到树莓派上,如果我继续执行“ 192.168.0.3/On.php”,则指示灯会亮起。 If i go on "192.168.0.3/off.php" the light turns off. 如果我继续执行“ 192.168.0.3/off.php”,指示灯将熄灭。 What i want to do is make this app for myself so that i don't have to keep changing the ip everytime i want to change the light's status, but simply press a button that loads the page in the background. 我想要做的是为自己创建这个应用程序,这样我就不必每次都想更改灯光状态时就不断更改IP,而只需按下一个按钮即可在后台加载页面。

PS I know how to add the button function. PS我知道如何添加按钮功能。 I only need to know how to load in background. 我只需要知道如何在后台加载。

Here is an example on how to send a GET request with a NSURLConnection to trigger the switch on your raspberry pi: 这是一个有关如何使用NSURLConnection发送GET请求以触发树莓派上的开关的示例:

func switchOn() {
    let url = NSURL(string: "http://192.168.0.3/On.php")
    let request = NSURLRequest(URL: url!)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        // do something with the response if you want to
    }
}

Just be aware that Apple introduced App Transport Security with iOS9. 请注意,Apple在iOS9中引入了App Transport Security That is a new security feature that enforces certain security practices when working with web requests. 这是一项新的安全功能,可在处理Web请求时强制执行某些安全措施。 For example it won't allow to send requests via HTTP, because it only allows HTTPS requests. 例如,它不允许通过HTTP发送请求,因为它仅允许HTTPS请求。 The good news is that you can override these security requirements by adding this to your project's Info.plist file: 好消息是,您可以通过将其添加到项目的Info.plist文件中来覆盖这些安全要求:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

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

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