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
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)
}
}
}
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
- Open terminal and run
sudo gem install cocoapods
to install cocoapods
- From your terminal, go to your project home
- Run
pod init
to initialize Podfile
- Open
Podfile
and paste following command
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftyJSON', '~> 2.2.1'
end
- Finally run
pod install
and it will add SwiftyJSON into you project
- Close xcode and open
.xcworkspace
instead of .xcodeproj
Now you are good to go
For more info, SwiftyJSON in cocoapods
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.
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
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"
}
}