简体   繁体   中英

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). The webpage is loaded on the raspberry and if i go on "192.168.0.3/On.php" the light turns on. If i go on "192.168.0.3/off.php" the light turns off. 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.

PS I know how to add the button function. 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:

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. That is a new security feature that enforces certain security practices when working with web requests. For example it won't allow to send requests via HTTP, because it only allows HTTPS requests. The good news is that you can override these security requirements by adding this to your project's Info.plist file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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