简体   繁体   English

使用SwiftyJSON处理JSON的示例

[英]Example handling JSON with SwiftyJSON

I would like to handle json with SwiftJSON, but I stacked. 我想用SwiftJSON处理json,但我堆叠了。 Does anyone show me example code? 有没有人给我看示例代码?

I tried to use this library. 我试图使用这个库。 https://github.com/SwiftyJSON/SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON

Although I placed SwiftyJSON.swift in the same project, I have error "No such module "SwiftyJSON"" So correct my code or show me example code handling json from web with swiftyJSON lib. 虽然我在同一个项目中放置了SwiftyJSON.swift,但我有错误“没有这样的模块”SwiftyJSON“”所以纠正我的代码或者向我展示使用swiftyJSON lib从web处理json的示例代码。

Here is my code: 这是我的代码:

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.
    }
}

Here is my Xcode capture 这是我的Xcode捕获

截图

If you added SwiftyJSON.swift to your project, you don't need to import it. 如果您将SwiftyJSON.swift添加到项目中,则无需import它。 It's already available. 它已经可用了。

Try: 尝试:

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)
        }
    }
}

Use this https://github.com/SwiftyJSON/SwiftyJSON version to get up to date SwiftyJSON 使用此https://github.com/SwiftyJSON/SwiftyJSON版本获取最新的SwiftyJSON

If you want to use import SwiftyJSON then you need to add using pod to do this, follow steps 如果要使用import SwiftyJSON则需要添加使用pod来执行此操作,请按照步骤操作

  1. Open terminal and run sudo gem install cocoapods to install cocoapods 打开终端并运行sudo gem install cocoapods来安装cocoapods
  2. From your terminal, go to your project home 从您的终端,到您的项目回家
  3. Run pod init to initialize Podfile 运行pod init以初始化Podfile
  4. Open Podfile and paste following command 打开Podfile并粘贴以下命令

platform :ios, '8.0' use_frameworks! target 'MyApp' do pod 'SwiftyJSON', '~> 2.2.1' end

  1. Finally run pod install and it will add SwiftyJSON into you project 最后运行pod install ,它会将SwiftyJSON添加到你的项目中
  2. Close xcode and open .xcworkspace instead of .xcodeproj 关闭xcode并打开.xcworkspace而不是.xcodeproj

Now you are good to go 现在你很高兴

For more info, SwiftyJSON in cocoapods 有关更多信息, 请使用cocoapods中的SwiftyJSON

The issue I've had is not following this bit of the CocoaPods instructions : 我遇到的问题不是遵循CocoaPods指令的这一点

Make sure to always open the Xcode workspace instead of the project file when building your project 在构建项目时,确保始终打开Xcode工作区而不是项目文件

I was opening the project instead of the workspace which resulted in the No Such Module error. 我打开项目而不是工作区导致No Such Module错误。

This went away after opening the workspace. 打开工作区后,这消失了。

Hi this is the link to a new Tutorial that explain very well how to working with JSON in Swift. 嗨,这是一个新教程的链接,可以很好地解释如何在Swift中使用JSON。

Parsing JSON the SwiftyJSON Way 解析JSON的SwiftyJSON方式

Api.swift 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 class object: Api类对象:

var ApiObj = Api()

login Api call: 登录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"
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM