Skip to content

Instantly share code, notes, and snippets.

@jjgod

jjgod/Network.swift

Last active Jul 7, 2016
Embed
What would you like to do?
//
// Network.swift
// ACArticle
//
// Created by Zhida Cheng on 7/6/16.
// Copyright © 2016 Zhida Cheng. All rights reserved.
//
import Foundation
struct ArticleInList{
let title: String
let authorName: String
let authorAvatar: String
let cover: String
let commentCount: Int
static func decode(j: AnyObject) -> ArticleInList?{
guard let
title = j["title"] as? String,
authorName = j["user"]??["username"] as? String,
authorAvatar = j["user"]??["userImg"] as? String,
cover = j["cover"] as? String,
commentCount = j["comments"] as? Int
else {return nil}
return ArticleInList(title: title, authorName:authorName, authorAvatar:authorAvatar, cover:cover, commentCount:commentCount)
}
}
//API Value Type
struct ACFunAPI{
static let base = URL(string:"http://api.aixifan.com")!
static let headers = [
"deviceType": "0",
"platform": "1",
"productId": "2000",
"Content-Type": "application/json"
]
enum ArticleCategory: Int{
case home = 110
case emotion = 73
case anime = 74
case manga = 75
case game = 164
}
enum ResourceType{
case articles(category: ArticleCategory)
}
}
//API Methods
extension ACFunAPI {
static func resourceURL(type: ResourceType) -> URL?{
switch type{
case .articles(let category):
let urlString = "searches/channel?sort=4&pageNo=2&pageSize=20&channelIds=\(category.rawValue)"
return URL(string: urlString, relativeTo: self.base)
}
}
static func request(type: ResourceType, callback: (Any) -> Void) {
// Common Network Operations
// 1. URL Settings
guard let url = resourceURL(type: type) else {return}
var request = URLRequest(url: url)
request.httpMethod = "GET"
headers.forEach{ (h,v) in request.addValue(v, forHTTPHeaderField: h)}
// 2. Task Setting
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {print(error); return}
guard let data = data else {return}
do {
let dictFromJson = try JSONSerialization.jsonObject(with: data, options: [])
// 4. Parse Raw JSON
guard let data = dictFromJson["data"] else {return}
guard let values = data!["list"] else {return}
print(values)
// 5. Parse to Native Struct
let articleList = values.map{j in
return ArticleInList.decode(j: j)
}
print(articleList)
//callback(dictFromJson)
} catch {
print(error)
}
}
// 3. Start Task
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.