Skip to content

Instantly share code, notes, and snippets.

@amazedkoumei
Created December 18, 2012 08:04
Show Gist options
  • Save amazedkoumei/4326002 to your computer and use it in GitHub Desktop.
Save amazedkoumei/4326002 to your computer and use it in GitHub Desktop.
ブログ貼付用
# -*- coding: utf-8 -*-
class SampleAPI
def initialize(content, &block)
@content = content
fetch do
block.call() if block
end
end
def fetch(&block)
q = @content
url = "http://sample.com/api"
query = BW::HTTP.get("#{url}?q=#{q}") do |res|
if res.ok?
# DispatchはNSURLConnectionDelegate内に書く!
@queue = Dispatch::Queue.new(q)
@queue.async{
doSomething()
block.call() if block
}
else
errorMessage = "Error!!"
block.call(errorMessage) if block
end
end
@connection = query.connection
end
def doSomething()
# 重い処理
end
def close()
# 閉じる!!
@connection.cancel() if !@connection.nil?
# 閉じる!!
@queue.suspend! if !@queue.nil?
end
end
# -*- coding: utf-8 -*-
class SampleViewController < UIViewController
def viewDidLoad()
super
content = content()
@webView = UIWebView.new.tap do |v|
v.frame = self.view.bounds
v.delegate = self
view.addSubview(v)
v.loadHTMLString(content, baseURL:nil)
end
end
def viewDidDisappear(animated)
super
# 閉じる!
# 12/12/18 deallocに移動
# @webView.stopLoading() if !@webView.nil?
# 閉じる!
if !@sampleAPIList.nil?
@sampleAPIList.each do |s|
s.close() if !s.nil?
end
end
end
def dealloc()
super
# 12/12/18 追記
# 開放前にdelegateに明示的にnilを設定すればOK
@webView.delegate = nil
end
def webViewDidFinishLoad(webView)
p "webViewDidFinishLoad"
# コンテンツにiframeがあると2回呼ばれるので1回しか実行したくない処理は要工夫!
if @contentText.nil?
javaScript = "$('body').text()"
@contentText= webView.stringByEvaluatingJavaScriptFromString(javaScript)
@contentList = @contentText.strip().split("\n")
@contentList.delete("")
# ここで非同期処理実行
@sampleAPIList = []
@contentList.each do |c|
@sampleAPIList<<SampleAPI.new(c) do |error|
if error.nil?
p "OK"
else
p error
end
end
end
end
end
def content()
preHtml = <<-EOS
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>SampleContent</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
aaa<br />
bbb<br />
ccc<br />
ddd
<iframe width="560" height="315" src="http://www.youtube.com/embed/kjLO6utw_Tc" frameborder="0" allowfullscreen></iframe>
</body>
</html>
EOS
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment