ProfileHomeModel, ProfileLocationModel, ProfileRequestManager, ProfileTableUserViewController 및 ProfileTableViewCell을 포함하는 5 개의 클래스를 만들었습니다. 내 목표는 json을 올바르게 구문 분석하고 데이터를 표시하는 것입니다. 요청 관리자 클래스에서 문제가 발생했습니다. 나는 완전히 새로운 신속합니다. swiftyJSON과 Alamofire를 사용하지 않고이 작업을하고 싶습니다.프레임 워크를 사용하지 않고 RequestManager 클래스를 만드는 법 swift
import Foundation
class ProfileRequestManager{
let urlPath = "*********"
let url = NSURL(string: urlPath)
let data = NSData(contentsOfURL: url!)
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary
print(jsonData)
let results = jsonData!.objectForKey("strengths") as? [NSDictionary] ?? []
for result in results {
print(result)
}
}
catch {
print("Something went wrong while parsing json data fetched from the API")
}
}
jsonData
{ "success": true, "profile": { "firstname": "Vignesh", "lastname": "Krish", "title": "Software Developer Intern", "designations": null, "specialty": "Computer Science", "location": "0", "email": "[email protected]", "phone": "4026136265", "biography": "Boxing and Travelling", "interests": "Watching movies", "skills": "Hozier and A.R Rahman", "goals": "becoming a software developer", "mentors": "Hardik Patel", "doh": "2016-05-09", "dob": "1994-06-08", "strengths": [ { "id": "4", "name": "Analytical", "description": "People exceptionally talented in the Analytical theme search for reasons and causes. They have the ability to think about all the factors that might affect a situation.", "color": "9c0000" }, { "id": "17", "name": "Focus", "description": "People exceptionally talented in the Focus theme can take a direction, follow through, and make the corrections necessary to stay on track. They prioritize, then act.", "color": "5c3a6e" }, { "id": "8", "name": "Communication", "description": "People exceptionally talented in the Communication theme generally find it easy to put their thoughts into words. They are good conversationalists and presenters.", "color": "da892f" }, { "id": "29", "name": "Responsibility", "description": "People exceptionally talented in the Responsibility theme take psychological ownership of what they say they will do. They are committed to stable values such as honesty and loyalty.", "color": "5c3a6e" }, { "id": "30", "name": "Restorative", "description": "People exceptionally talented in the Restorative theme are adept at dealing with problems. They are good at figuring out what is wrong and resolving it.", "color": "5c3a6e" } ], "settings": { "enable_sms": "0" } } }
내가 할 캐치에
의 I가지고있어 오류가 위의 그것 모두를 반환하기 위해 노력하고있어. Xcode
에서 예상되는 선언 오류가 발생합니다. 나는 중괄호를 확인했다.
알아내는 데 도움을 주셔서 감사합니다.
또한 보안을 위해 URL을 포함 할 필요가 없습니다. 나는 그것이 도움이되기를 바랍니다.
또한 모든 값을 별도의 셀에 표시하려고합니다. 이것은 내가 지금 가지고있는 것입니다.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileCell", forIndexPath: indexPath) as! ProfileUserTableViewCell
cell.firstName?.text = firstName
cell.lastName?.text = lastName
cell.title?.text = title
return cell
}
}
어떻게 해결할 수 있는지 알고 계십니까?
이것은 현재 상황입니다. 테이블 뷰 셀에 표시 할 수 없습니다. 이 문제는 json 값을 레이블에 할당하는 것과 관련이있는 것으로 보입니다.
수입 UIKit
클래스 ProfileUserTableViewController :있는 UITableViewController {여기
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
//retrieving json from server
let requestURL: NSURL = NSURL(string: "https:******************")!
//Your baseURL
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine")
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
return
}
// print("JSONDictionary! \(JSONDictionary)")
if let profile = JSONDictionary["profile"] as? NSDictionary {
print(profile)
//This is where we should begin parsing json into whatever you want to
let firstName = profile["firstName"] as? String
let lastName = profile["lastName"] as? String
let title = profile["title"] as? String
print(firstName!, lastName, title!)
// let settings = profile["settings"] as? NSDictionary
//
// let enableSMS = settings!.valueForKey("enable_sms") as? String
// print(enableSMS!)
//to parse commentTotals content from api
let commentTotals = profile["commentTotals"] as? NSArray
for eachItem in commentTotals! {
let total = eachItem.valueForKey("total") as? String
let id = eachItem.valueForKey("id") as? String
print(total!,id!)
}
//to parse strength contents from api
let strengths = profile["strengths"] as? NSArray
for eachItem in strengths! {
let color = eachItem.valueForKey("color") as? String
let description = eachItem.valueForKey("description")
let id = eachItem.valueForKey("id")
let name = eachItem.valueForKey("name")
print(name!, description!, color!, id!)
}
}
}
catch let JSONError as NSError {
print("\(JSONError)")
}
}
}
task.resume()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileCell", forIndexPath: indexPath) as! ProfileUserTableViewCell
cell.firstName?.text = [indexPath.row].firstName
cell.lastName?.text = [indexPath.row].lastName
cell.title?.text = [indexPath.row].title
return cell
}
if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileCell2", forIndexPath: indexPath) as! ProfileUserTableViewCell
cell.score?.text = [indexPath.row].score
cell.received?.text = [indexPath.row].received
cell.given?.text = [indexPath.row].given
return cell
}
if indexPath.row == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileCell3", forIndexPath: indexPath) as! ProfileUserTableViewCell
cell.coreValueComments1?.text = [indexPath.row].total
cell.coreValueComments2?.text = [indexPath.row].total
cell.coreValueComments3?.text = [indexPath.row].total
cell.coreValueComments4?.text = [indexPath.row].total
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileCell4", forIndexPath: indexPath) as! ProfileUserTableViewCell
cell.strength1?.text = [indexPath.row].name
cell.strength2?.text = [indexPath.row].name
cell.strength3?.text = [indexPath.row].name
cell.strength4?.text = [indexPath.row].name
return cell
}
}
}
감사합니다. 나는 또 다른 질문이있다. 내 UI에 json 값을 표시하려고합니다. 나는 코드와 질문을 메인 포스트에 첨부했다. 너 나 좀 도와 줄래? –
UI에 데이터를 어떻게 표시 하시겠습니까? tableView? – amagain
또한, 이것은 코드를 작성하는 정확한 접근 방식이 아닙니다. 이 코드는 무언가를하기위한 목적으로 사용됩니다. 디자인 패턴을 공부하고 모든 영역에서 MVC 패턴을 따르십시오. – amagain