5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOSでSwiftからwebviewに値を渡す

5
Last updated at Posted at 2016-01-21

iOSガワネイティブでSwiftから値を受け取る

上記の記事を参考に実装したのだが、webview側で値が取れない・・・
いろいろ調べたら、戻すときのheaderに

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Headers

が必要だったようです。(多分)

sample.swift
    private func sendBackPlainText(str: String, status_code:Int) {
        
        if let data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding) {
            let headers = [
                "Content-Type": "text/plain",
                "Content-Length": "\(data.length)",
                "Content-Encoding": "UTF-8",
                "Access-Control-Allow-Origin" : "*", //ここ
                "Access-Control-Allow-Headers" : "*" //ここ
            ]
            
            let response = NSHTTPURLResponse(URL: self.request.URL!,
                statusCode: status_code,
                HTTPVersion: "1.1",
                headerFields: headers)
            self.client?.URLProtocol(self,
                didReceiveResponse: response!,
                cacheStoragePolicy: NSURLCacheStoragePolicy.AllowedInMemoryOnly)
            self.client?.URLProtocol(self, didLoadData: data)
            self.client?.URLProtocolDidFinishLoading(self)
        }
    }
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?