18

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

I tried to use this library. 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.

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

Screenshot

1
  • It may be that you are just not opening the right file. Make sure you are opening the xcworkspace file, not xcodeproj file.
    – mfaani
    Jul 20, 2016 at 1:01

5 Answers 5

25

If you added SwiftyJSON.swift to your project, you don't need to import it. 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)
        }
    }
}
6
  • Thanks! It works well! But I have a question. Although the first parameter in a method does not need parameter name, why does we need "data:" in function JSON. If I do not use the parameter name, I have trouble below. Nov 5, 2014 at 14:34
  • if data != nil { var hoge = JSON(data!) // Cannot invole 'init' with an argument of type '@lvalue NSData' println(hoge) } Nov 5, 2014 at 14:34
  • JSON(obj) is to convert Swift object(e.g. Dictionary) to JSON object. JSON(data:dat) is to convert NSData to JSON object
    – rintaro
    Nov 5, 2014 at 14:51
  • I got it! Thanks your answer with the link to SwiftJson source code which declares the definition of JSON function. Nov 10, 2014 at 5:07
  • Ok, I did that.... but now I am getting TONS of errors telling me to replace "as" with "as!" al over the place. Why?
    – Josh
    May 14, 2015 at 8:59
9

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

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

  1. Open terminal and run sudo gem install cocoapods to install cocoapods
  2. From your terminal, go to your project home
  3. Run pod init to initialize Podfile
  4. Open Podfile and paste following command

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
  2. Close xcode and open .xcworkspace instead of .xcodeproj

Now you are good to go

For more info, SwiftyJSON in cocoapods

2
  • and build the project after that.
    – OWADVL
    May 18, 2016 at 12:45
  • 1
    "6. Close xcode and open .xcworkspace instead of .xcodeproj" is enough for me. May 27, 2016 at 7:12
2

The issue I've had is not following this bit of the CocoaPods instructions:

Make sure to always open the Xcode workspace instead of the project file when building your project

I was opening the project instead of the workspace which resulted in the No Such Module error.

This went away after opening the workspace.

1

Hi this is the link to a new Tutorial that explain very well how to working with JSON in Swift.

Parsing JSON the SwiftyJSON Way

3
  • Thanks! It's really useful page! Nov 10, 2014 at 5:08
  • That example is only half done, it only shows parsing data not writing. May 11, 2015 at 17:43
  • 1
    This doesn't talk about the SwiftyJSON library, it talks about a different Swifty JSON library. Feb 18, 2017 at 10:09
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 class object:

var ApiObj = Api()

login Api call:

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.