使用SwiftyJSON处理JSON的示例

时间:2014-11-05 10:11:53

标签: ios json swift xcode6

我想用SwiftJSON处理json,但我堆叠了。 有没有人给我看示例代码?

我试图使用这个库。 https://github.com/SwiftyJSON/SwiftyJSON

虽然我将SwiftyJSON.swift放在同一个项目中,但我有错误"没有这样的模块" SwiftyJSON"" 因此,请更正我的代码或向我展示使用swiftyJSON lib从web处理json的示例代码。

这是我的代码:

import UIKit
import SwiftyJSON // No such module "SwiftyJSON"

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = NSURL(string: "http://express.heartrails.com/api/json?method=getPrefectures")

        var request = NSURLRequest(URL: url!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)

        var json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary

        var hoge = JSON(data)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

这是我的Xcode捕获

Screenshot

5 个答案:

答案 0 :(得分:25)

如果您将SwiftyJSON.swift添加到项目中,则无需import。它已经可用了。

尝试:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://express.heartrails.com/api/json?method=getPrefectures")
        var request = NSURLRequest(URL: url!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        if data != nil {
            var hoge = JSON(data: data!)
            println(hoge)
        }
    }
}

答案 1 :(得分:9)

使用此https://github.com/SwiftyJSON/SwiftyJSON版本获取最新的SwiftyJSON

如果您想使用import SwiftyJSON,则需要添加使用pod 要执行此操作,请按照步骤

  1. 打开终端并运行sudo gem install cocoapods以安装cocoapods
  2. 从您的终端,转到您的项目主页
  3. 运行pod init初始化Podfile
  4. 打开Podfile并粘贴以下命令
  5. platform :ios, '8.0' use_frameworks! target 'MyApp' do pod 'SwiftyJSON', '~> 2.2.1' end

    1. 最后运行pod install,它会将SwiftyJSON添加到您的项目中
    2. 关闭xcode并打开.xcworkspace而不是.xcodeproj
    3. 现在你很高兴

      有关详细信息,请SwiftyJSON in cocoapods

答案 2 :(得分:2)

我遇到的问题不是关注this bit of the CocoaPods instructions

  

确保始终打开Xcode工作区而不是项目   构建项目时的文件

我正在打开项目而不是工作区导致No Such Module错误。

打开工作区后,这就消失了。

答案 3 :(得分:1)

嗨,这是一个新教程的链接,可以很好地解释如何在Swift中使用JSON。

Parsing JSON the SwiftyJSON Way

答案 4 :(得分:0)

Api.swift

import UIKit

extension NSMutableData
{
    func appendString(string: String)
    {
         let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    appendData(data!)
    }
}

class Api: NSObject, NSXMLParserDelegate
{

func CallGetApi(str: String  ) -> JSON
{
    let url = NSURL(string: "http://"+str)
    let request = NSURLRequest(URL: url!)
    let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)

    if data != nil
    {
        let dataDict = JSON(data: data!)
        return dataDict
    }
    return JSON(integerLiteral:5)
}

func isConnectedToNetwork() -> Bool
{
    var Status:Bool = false
    let url = NSURL(string: "http://google.com/")
    let request = NSURLRequest(URL: url!)
    let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)

    if data != nil
    {
        Status = true
    }
    return Status
}

func CallPostApi(urlStr: String , postStr: String  ) -> JSON
{
    print(postStr)

    let link = "http://"+urlStr
    print("\(link)/?\(postStr)")
    let url = NSURL(string: link);
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 10.0)

    request.HTTPMethod = "POST";
    request.HTTPBody = postStr.dataUsingEncoding(NSUTF8StringEncoding);


    if let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
    {
        let dataDict = JSON(data: data)
        print(dataDict)
        return dataDict
    }

    if self.isConnectedToNetwork() == false
    {
        return JSON(integerLiteral:6)
    }
    return JSON(integerLiteral:5)
}

func CallUpdatePictures(urlStr: String , parameters: [String: String]?, pics: Array<UIImage>  ) -> JSON
{
    let link = "http://"+urlStr
    let url = NSURL(string: link);
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 50.0)

    print(link)

    request.HTTPMethod = "POST"

    let boundary:String = "---------------------------14737809831466499882746641449"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    let body:NSMutableData = NSMutableData()

    if parameters != nil
    {
        for (key, value) in parameters!
        {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    var i:Int = 1
    for pic in pics
    {
        let img:UIImage = self.resizeImage(pic, maxHeight: 216, maxWidth: 384)
        let imageData = UIImagePNGRepresentation(img)
        //let imageData = UIImageJPEGRepresentation(img, 1.0)


        if imageData != nil
        {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"image\(i)\"; filename=\"image.png\"\r\n")
            body.appendString("Content-Type: image/png\r\n\r\n")
            body.appendData(imageData!)
            body.appendString("\r\n")
            i=i+1
        }
    }

    body.appendString("--\(boundary)--\r\n")
    request.setValue("\(body.length)", forHTTPHeaderField:"Content-Length")
    request.HTTPBody = body

    if let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
    {
        let dataDict = JSON(data: data)
        print(dataDict)
        return dataDict
    }

    if self.isConnectedToNetwork() == false
    {
        return JSON(integerLiteral:6)
    }
    return JSON(integerLiteral:5)
}

func CallUpdatePicture(urlStr: String , parameters: [String: String]?, pic: UIImageView  ) -> JSON
{
    let link = "http://"+urlStr
    let url = NSURL(string: link);
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 50.0)

    request.HTTPMethod = "POST"

    let boundary:String = "---------------------------14737809831466499882746641449"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    let body:NSMutableData = NSMutableData()

    if parameters != nil
    {
        for (key, value) in parameters!
        {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    if pic.image != nil
    {
        let img:UIImage = self.resizeImage(pic.image!, maxHeight: 200, maxWidth: 200)
        let imageData = UIImagePNGRepresentation(img)

        if imageData != nil
        {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n")
            body.appendString("Content-Type: image/png\r\n\r\n")
            body.appendData(imageData!)
            body.appendString("\r\n")
        }
    }

    body.appendString("--\(boundary)--\r\n")
    request.setValue("\(body.length)", forHTTPHeaderField:"Content-Length")
    request.HTTPBody = body

    if let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
    {
        let dataDict = JSON(data: data)
        print(dataDict)
        return dataDict
    }

    if self.isConnectedToNetwork() == false
    {
        return JSON(integerLiteral:6)
    }
    return JSON(integerLiteral:5)
}

func resizeImage(image:UIImage, maxHeight:Float, maxWidth:Float) -> UIImage
{
    var actualHeight:Float = Float(image.size.height)
    var actualWidth:Float = Float(image.size.width)

    var imgRatio:Float = actualWidth/actualHeight
    let maxRatio:Float = maxWidth/maxHeight

    if (actualHeight > maxHeight) || (actualWidth > maxWidth)
    {
        if(imgRatio < maxRatio)
        {
            imgRatio = maxHeight / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxHeight;
        }
        else if(imgRatio > maxRatio)
        {
            imgRatio = maxWidth / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = maxWidth;
        }
        else
        {
            actualHeight = maxHeight;
            actualWidth = maxWidth;
        }
    }

    let rect:CGRect = CGRectMake(0.0, 0.0, CGFloat(actualWidth) , CGFloat(actualHeight) )
    UIGraphicsBeginImageContext(rect.size)
    image.drawInRect(rect)

    let img:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    let imageData:NSData = UIImageJPEGRepresentation(img, 1.0)!
    UIGraphicsEndImageContext()

    return UIImage(data: imageData)!
}
}

Api类对象:

var ApiObj = Api()

登录Api电话:

        let postString = "uid=\(Email_Txt.text!)&pwd=\(Password_Txt.text!)"
        var dataDict=ApiObj.CallPostApi("user/login", postStr: postString)

        if (dataDict.null == nil)
        {
            if dataDict == 6
            {
                 msg = "Network not available"
            }
            else if dataDict.object.objectForKey("token") != nil
            {
                 msg = "Successfull login "
            }
            else if dataDict.object.objectForKey("err") != nil
            {
                msg = "Invalid email or password"
            }
        }