主要是一个搜索电影,显示电影信息的小程序,开发坏境是xcode7.0,swift2.0
func searchIMDBWithContent(content : String){
//在这里需要将传进来的字符串进行格式化(将空格用%20代替)
// let nospaceString = content.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let nospaceString = content.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet)
let urlPath = NSURL(string: "http://www.omdbapi.com/?t=\(nospaceString!)")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(urlPath!) {
data, response, error -> Void in
if (error != nil){
print(error?.localizedDescription)
}
//解析可能会出现错误,因此需要使用try来进行处理
do{
let jsonResult = try //在类方法之前加try
NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)as! Dictionary <String , String>
//需要在主线程线程来执行控件显示的代码
if let apiDelegate = self.delegate{
dispatch_async(dispatch_get_main_queue()){
self.delegate?.didfinshIMDbSearch(jsonResult)
}
}
}catch{
print("格式化数据失败")
}
}
task.resume()//这一步是必须的
}
在网络请求的时候,需要注意是在iOS9中,程序的“应用程序传输安全协议”默认是开的,我们需要对它进行配置,程序才能进行网络的访问
有关于配置的方法,在这里。
func blurBackgroundUsingImage(image: UIImage){
let frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
let imageView = UIImageView(frame: frame)
imageView.image = image
imageView.contentMode = .ScaleAspectFill
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = frame
let transparentWhiteView = UIView(frame: frame)
transparentWhiteView.backgroundColor = UIColor(white: 1.0, alpha: 0.30)
let views:Array = [imageView,blurEffectView,transparentWhiteView]
for index in 0 ..< views.count{
if let _ = self.view.viewWithTag(index+1){
let oldView = self.view.viewWithTag(index+1)
oldView?.removeFromSuperview()
}
let viewToIsert = views[index]
self.view.insertSubview(viewToIsert, atIndex: index+1)
viewToIsert.tag = index+1
}
}
其实就是创建3个视图添加上去。