var array = [1,4,7]
// 数组内插入一个新的数组
array.insertContentsOf([9,6], at:1)
// 替换某个位置为一个新的数组
array.replaceRange(0...2, with: [1,1,0])
// 排序
// 数组排序还可以调用 sort方法,与sorted不一样的是,sort排序是修改数组本身排序且不会返回结果,sorted则返回排序后的结果但不修改数组本身。所以调用sort方法的数组只能为var定义的变量
array.sortInPlace { $0 < $1 }
import UIKit
class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionDataDelegate {
var session:NSURLSession!
override func viewDidLoad() {
super.viewDidLoad()
//let config = NSURLSessionConfiguration.backgroundSessionConfiguration("back")//不赞成使用
//let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("back")//委托中不能使用,使用系统处理下载,就算APP没有运行了,也可以实现
//let config = NSURLSessionConfiguration.ephemeralSessionConfiguration();//这个是临时数据下载,适用于小数据下载
let config = NSURLSessionConfiguration.defaultSessionConfiguration()//默认配置
config.timeoutIntervalForRequest = 15 //连接超时时间
session = NSURLSession(configuration: config, delegate: self, delegateQueue:nil)//队列中,如果想要程序在主线程中执行,可以使用NSOperationQueue.mainQueue()
let url = NSURL(string: "http://www.wutongwei.com")
let task = session.dataTaskWithURL(url!, completionHandler: { (
data, response, error) -> Void in
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Done!")
self.session.finishTasksAndInvalidate() //确保执行完成后,释放session
if error == nil {
let manager = NSFileManager()
//
var error:NSError?
var destinationPath = manager.URLForDirectory(NSSearchPathDirectory.CachesDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: url, create: true, error: &error)!
//
let componenetsOfUrl = url?.absoluteString!.componentsSeparatedByString("/")
let index = componenetsOfUrl!.count - 1
let fileNameFromUrl = componenetsOfUrl![index]
destinationPath = destinationPath.URLByAppendingPathComponent(fileNameFromUrl)
//
manager.moveItemAtURL(url!, toURL: destinationPath, error: nil)
let message = "保存下载数据到 = \(destinationPath)"
self.displayAlertWithTitle("Success", message: message)
}else{
self.displayAlertWithTitle("Error", message: "不能下载这数据,一个错误抛出")
}
})
task.resume() //这个是启动任务的,不调用,则不会执行请求
}
func displayAlertWithTitle(title:String,message:String){
let controller = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
controller.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
///
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}