ios 使用 SwiftyJSON 处理 JSON 的示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26754481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:31:15  来源:igfitidea点击:

Example handling JSON with SwiftyJSON

iosjsonswiftxcode6

提问by tatsuya.yokoyama

I would like to handle json with SwiftJSON, but I stacked. Does anyone show me example code?

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

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 捕获

Screenshot

截屏

回答by rintaro

If you added SwiftyJSON.swiftto your project, you don't need to importit. It's already available.

如果您添加SwiftyJSON.swift到您的项目中,则不需要import它。它已经可用。

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

回答by Omar Faruqe

Use this https://github.com/SwiftyJSON/SwiftyJSONversion to get up to date SwiftyJSON

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

If you want to use import SwiftyJSONthen you need to add using pod to do this, follow steps

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

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

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

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

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

Now you are good to go

现在你可以走了

For more info, SwiftyJSON in cocoapods

有关更多信息,请参阅 cocoapods 中的 SwiftyJSON

回答by Marcus Leon

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.

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

回答by Alessio Marzoli

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

以 SwiftyJSON 方式解析 JSON

回答by Jayesh Miruliya

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