본문 바로가기

IOS/러닝패스

[#C3 SWIFT3] SNS 같은 FEED를 만드는 방법

IOS에서 FEED 스크린을 구현하기 위해 CollectionView 컴포넌트를 이용할 수 있습니다.


우선, Main.storyboard에 CollectionView 컴포넌트를 추가합니다.




추가된 CollectionView의 하위 객체 CustomCell에 Custom Class를 지정한 후, 라벨을 추가하고 이를 Outlet 연결합니다.




( CustomCell 객체 = Feed 객체 )


CustomCell.swift


1
2
3
4
5
6
class CustomCell:UICollectionViewCell{
    
    @IBOutlet weak var nameText: UILabel!
    
}
 
cs


이제 ViewController에서 CollectionView를 Outlet 연결하고, 델리게이트를 추가합니다. 데이터는 다음과 같은 형식을 사용합니다.


1
2
3
4
5
6
7
8
9
{
"name"="johns",
"name"="finaly",
"name"="don",
"name"="fulazia",
"name"="scott",
"name"="fiance",
"name"="triss",
}
cs


SOURCE CODE


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
//  ViewController.swift
//  Created by Trendy Develope
 
import UIKit
 
class ViewController: UIViewController, UICollectionViewDataSource, 
UICollectionViewDelegate, UICollectionViewDelegateFlowLayout  {
    
    var list:[MyStruct] = [MyStruct]()
    
    struct MyStruct
    {
        
        var name = ""
        
        init(_ data:NSDictionary)
        {
            
            if let add = data["name"asString
            {
                self.name = add
//add other data here
            }
            
        }
    }
 
    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let url = "name_data_url"
        
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        
        collectionView.collectionViewLayout = layout
        
        get_data(url)
    }
    
    func get_data(_ link:String)
    {
        let url:URL = URL(string: link)!
        let session = URLSession.shared
        
        let request = URLRequest(url: url)
        
        let task = session.dataTask(with: request, completionHandler: {
            (data, response, error) in
            
            self.extract_data(data)
            
        })
        
        task.resume()
    }
    
    func extract_data(_ data:Data?)
    {
        let json:Any?
        if(data == nil)
        {
            return
        }
        
        do
        {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch
        {
            return
        }
        
        
        guard let data_array = json as? NSArray else
        {
            return
        }
        
        for i in 0 ..< data_array.count
        {
            if let data_object = data_array[i] as? NSDictionary
            {
                list.append(MyStruct(data_object))
            }
        }
        
        refresh_now()
        
    }
    
    func refresh_now()
    {
        DispatchQueue.main.async (
            execute:
            {
                self.collectionView.reloadData()
        }
        )
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int-> Int
    {
        return list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
 -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell"for: indexPath)
 as! CustomCell
        
        //feed screen corner radius
        cell.layer.cornerRadius = 3
        
        /*list[indexPath.row].other_data*/
        cell.nameText.text = list[indexPath.row].name
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: 
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 192, height: 192)
    }
 
 
}
 
 
cs

 

코드는 추출한 데이터를 구조체 MyStruct에 추가합니다. 메소드는 cell에 대한 각종 속성을 설정하며 포함하는 객체 (라벨)에 데이터를 지정합니다.


구조체의 각 데이터는 메소드에서 list[indexPath.row].data 로 가져올 수 있습니다.


참고


JSON 데이터를 포함한 URL 생성 [#G2 : PHP를 이용해 DB[MySQL]의 데이터를 내보내는 방법]


보낸 데이터를 DB에 저장하는 방법 [#G1 : PHP를 이용해 DB[MySQL]에 데이터를 저장하는 방법]