2016年2月

swift实现http上传

//
//  ViewController.swift
//  http请求
//
//  Created by admin on 16/2/26.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.uploadFile()
    }
    func uploadFile()
    {
        let urlStr = "http://test.com/upload.php"
        let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)

        var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        // 设置上传文件所需要的信息
        self.setUploadRequest(&request,filePath: NSBundle.mainBundle().pathForResource("2.jpg", ofType: nil)!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response: NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            let json:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
            print(json)
        }
    }
    // 设置上传文件的头
    func setUploadRequest(inout request:NSMutableURLRequest,filePath:String)->NSMutableURLRequest
    {
        let seperator = "jin"
        // 设置请求类型
        request.HTTPMethod = "post"
        // 设置http头
        // Content-Type multipart/form-data; boundary(分隔符)=(可以随便写, 但是不能有中文)
        let header = "multipart/form-data; boundary=\(seperator)"
        request.setValue(header, forHTTPHeaderField: "Content-Type")

        // 拼接数据
        let bodyData = NSMutableData()
        // \r\n--(可以随便写, 但是不能有中文)\r\n
        var str = "\r\n--\(seperator)\r\n"
        bodyData.appendData(str.dataUsingEncoding(NSUTF8StringEncoding)!)

        // Content-Length(文件的大小)    这个不用写
        // Content-Disposition: form-data; name="userfile(php脚本中用来读取文件的字段)"; filename="demo.json(要保存到服务器的文件名)"\r\n
        str = "Content-Disposition: form-data; name=\"uploadFile\"; filename=\"newFile.jpg\"\r\n"
        bodyData.appendData(str.dataUsingEncoding(NSUTF8StringEncoding)!)

        // Content-Type: application/octet-stream(上传文件的类型)\r\n\r\n
        str = "Content-Type: application/octet-stream\r\n\r\n"
        bodyData.appendData(str.dataUsingEncoding(NSUTF8StringEncoding)!)

        // 要上传的文件的二进制流
        let fileData = NSData(contentsOfFile: filePath)
        bodyData.appendData(fileData!)

        // \r\n--(可以随便写, 但是不能有中文)--\r\n
        str = "\r\n--\(seperator)--\r\n"
        bodyData.appendData(str.dataUsingEncoding(NSUTF8StringEncoding)!)
        request.HTTPBody = bodyData
        return request
    }
}

发送http请求(get,post)

//
//  ViewController.swift
//  http请求
//
//  Created by admin on 16/2/26.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.post()
    }
    func post()
    {
        let urlStr = "http://test.com/login.php"
        // url中含有中文的话需要编码下
        let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)

        // 初始化可变请求,用以之后改变对象的属性
        let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        request.HTTPMethod = "post"
        // 设置post数据,为字符串格式
        let postData = "username=张三&password=zhang"
        // 设置请求的data,需要转换成二进制的数据类型
        request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            if data != nil
            {
                let json:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                print(json)
            }

        }
    }
    func get()
    {
        let urlStr = "http://test.com/login.php?username=张三&password=zhang"
        // url中含有中文的话需要编码下
        let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            if data != nil
            {
                let json:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                print(json)
            }

        }
    }
}

xml解析(DOM)

//
//  ViewController.swift
//  xml解析
//
//  Created by zhang on 16/2/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.decodeXML()
    }
    /**
     使用步骤
     First add the files from the Pod/Classes folder in this project to your source tree, then include them somewhere in your code,

     In Xcode choose the project file (in the project navigator, the top item).

     In the list choose your project target and select 'Build Settings' at the top of the window. Then you should see a list of build options.

     Add this line to 'Header Search Paths' (use search bar to find the right option) /usr/include/libxml2

     Add this line to 'Other Linker Flags': -lxml2
     */
    func decodeXML()
    {
        let url = NSURL(string: "http://localhost/videos.xml")
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in

            // 实例化GDataXMLDocument
            let xml:GDataXMLDocument! = try? GDataXMLDocument(data: data!)
            // 循环根节点的子节点
            for element in xml.rootElement().children()
            {
                let video = Video()
                // 循环数据节点的属性并完成赋值
                for videoElment in element.children()
                {
                    video.setValue(videoElment.stringValue, forKey: videoElment.name)
                }
                // 去除节点属性值对象数组
                let attrs = element.valueForKey("attributes")! as! [GDataXMLNode]
                // 完成对象属性的赋值
                for attr in attrs
                {
                    video.setValue(attr.stringValue(), forKey: attr.name())
                }
            }
        }
    }
    func useNSNumber()
    {
        let url = NSURL(string: "http://localhost/demo.json")
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            print(data)
            if data != nil
            {
                let json:AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                let mes = Message()
                mes.setValuesForKeysWithDictionary(json as! [String : AnyObject])
                print(mes.valueForKey("messageId"))

            }
        }
    }
}
class Message:NSObject {
    // 数据类型为int的时候当服务器返回 null 的时候会抱下面的错误,用 NSNumber 就不会
    // this class is not key value coding-compliant for the key messageId
    var messageId:NSNumber!
    var message:String!
}
class Video:NSObject {
    var name:String!
    var length:String!
    var videoURL:String!
    var imageURL:String!
    var desc:String!
    var teacher:String!
    var videoId:String!
}

xml解析(SAX)

//
//  ViewController.swift
//  xml解析
//
//  Created by admin on 16/2/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UITableViewController,NSXMLParserDelegate {

    lazy var videos:[Video] = []
    lazy var nodeString:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.decodeXml()

    }
    @IBAction func decodeXml()
    {
        let url = NSURL(string: "http://test.com/videos.xml")
        // 忽略缓存数据
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { [weak self] (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            let xml = NSXMLParser(data: data!)
            xml.delegate = self
            xml.parse()
        }
    }
    // 开始解析文档
    func parserDidStartDocument(parser: NSXMLParser)
    {
        self.videos.removeAll()
    }

    // 开始节点
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        if elementName == "video"
        {
            self.videos.append(Video())
        }
        self.nodeString = ""
    }

    // 获得文本内容
    func parser(parser: NSXMLParser, foundCharacters string: String)
    {
        self.nodeString = "\(self.nodeString)\(string)"
    }
    // 结束节点
    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if elementName != "video" && elementName != "videos"
        {
            self.videos[self.videos.count - 1].setValue(self.nodeString, forKey: elementName)
        }
    }
    // 结束解析文档
    func parserDidEndDocument(parser: NSXMLParser)
    {
        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    }
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifer = "xmlCell"
        var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifer)
        if cell == nil
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifer)
        }
        cell.textLabel?.text = self.videos[indexPath.row].name
        cell.detailTextLabel?.text = self.videos[indexPath.row].videoURL
        return cell
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.videos.count
    }
}
class Video:NSObject {
    var name:String!
    var length:String!
    var videoURL:String!
    var imageURL:String!
    var desc:String!
    var teacher:String!
}