2017-03-29 3 views
-1

안녕 얘들 아, 내 장치에서 연락처 목록을 가져온 응용 프로그램에서 작업하고 있는데 연락처를 "추가"할 수있는 옵션이 주어졌지만 기능면에서별로 도움이되지 않습니다. 나는 최고의 코더가 아니기 때문에 내 말을 들어야한다. 내가 뭘하려고 데이터/선택한 테이블보기 셀을 가지고 다른 페이지에 표시 할 수 있습니다. 나는 다른 페이지에 데이터를 표시하려고 시도했지만 내 오버라이드 기능을 이동할 때 오류가 발생하므로이 작업을 수행해야한다고 생각합니다. 그게 내가 데이터를 가져 가야한다고 믿게합니다. 나는 믿습니다. newContact? 변수로 설정 한 다음 새보기 컨트롤러를 만들고 오류없이 코드를 추가 할 수있는 새 페이지에 표시하십시오.선택한 셀을 다른보기 컨트롤러에 보내는 방법은 무엇입니까?

기본적으로 내 JSON 데이터를 저장하는 위치를 알아 내야합니다. 가능한 경우 해당 문자열을 해당 문자열로 설정해야합니다. 새보기 컨트롤러에 보내거나 코드 I로 데이터베이스에 전송할 수 있습니다. 이미 만들었습니다.

내가 얻는 오류와 정확한 코드가 무엇 때문에 진술을 어디에 입력해야할지 모르겠습니다.

내가 수행하려고 시도하고있는 것에 대해 끔찍한 설명을 드려 죄송합니다. 수행해야 할 작업을 파악하고 있지만 초보자입니다.

내 전화에서 연락처를 가져 와서 액세스하는 내 마스터보기 컨트롤러.

import UIKit 
import Contacts 
import ContactsUI 

class MainViewController: UIViewController { 

@IBOutlet weak var textField: UITextField! 
@IBOutlet weak var tableView: UITableView! 

var store = CNContactStore() 
var contacts: [CNContact] = [] 

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

//MARK: - User Actions 

@IBAction func contactListPressed(_ sender: AnyObject) { 
    let contactPickerViewController = CNContactPickerViewController() 
    contactPickerViewController.delegate = self 
    present(contactPickerViewController, animated: true, completion:  nil) 
} 

@IBAction func addContactPressed(_ sender: AnyObject) { 
    let newContact = CNMutableContact() 

    newContact.givenName = "Apps" 
    newContact.familyName = "Foundations" 
    newContact.nickname = "AF" 

    if let image = UIImage(named: "logo-apps-foundation.jpg"), 
     let data = UIImagePNGRepresentation(image){ 
     newContact.imageData = data 
    } 

    let phone = CNLabeledValue(label: CNLabelWork, value: CNPhoneNumber(stringValue: "+441234567890")) 
    newContact.phoneNumbers = [phone] 

    let email = "" //Your Input goes here 
    let Email = CNLabeledValue(label:CNLabelWork, value: email as NSString) 
    newContact.emailAddresses = [Email] 


    newContact.jobTitle = "Apps Foundation" 
    newContact.organizationName = "Apps Foundation" 
    newContact.departmentName = "IT" 

    let facebookProfile = CNLabeledValue(label: "Facebook", value: CNSocialProfile(urlString: "https://www.facebook.com/appsfoundation", username: "AppsFoundation", userIdentifier: "appsfoundation", service: CNSocialProfileServiceFacebook)) 
    let twitterProfile = CNLabeledValue(label: "Twitter", value: CNSocialProfile(urlString: "https://twitter.com/AppsFoundation", username: "AppsFoundation", userIdentifier: "appsfoundation", service: CNSocialProfileServiceTwitter)) 
    newContact.socialProfiles = [facebookProfile, twitterProfile] 

    let skypeProfile = CNLabeledValue(label: "Skype", value: CNInstantMessageAddress(username: "AppsFoundation", service: CNInstantMessageServiceSkype)) 
    newContact.instantMessageAddresses = [skypeProfile] 

    var birthday = DateComponents() 
    birthday.year = 1991 
    birthday.month = 1 
    birthday.day = 1 
    newContact.birthday = birthday 

    let request = CNSaveRequest() 
    request.add(newContact, toContainerWithIdentifier: nil) 
    do { 
     try store.execute(request) 
     let alert = UIAlertController(title: "Contacts iOS 9", message: "New contact has been created", preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) 
     present(alert, animated: true, completion: nil) 
    } catch let error{ 
     print(error) 
    } 
} 

@IBAction func textFieldValueChanged(_ sender: AnyObject) { 
    if let query = textField.text { 
     findContactsWithName(query) 
    } 
} 

//MARK: - Private Methods 

func findContactsWithName(_ name: String) { 
    AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in 
     if accessGranted { 
      DispatchQueue.main.async(execute: {() -> Void in 
       do { 
        let predicate: NSPredicate = CNContact.predicateForContacts(matchingName: name) 
        let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()] as [Any] 
        self.contacts = try self.store.unifiedContacts(matching: predicate, keysToFetch:keysToFetch as! [CNKeyDescriptor]) 
        self.tableView.reloadData() 
       } 
       catch { 
        print("Unable to refetch the selected contact.") 
       } 
      }) 
     } 
    }) 
} 

func updateContact(_ contactIdentifier: String) { 
    do { 
     let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactPhoneNumbersKey, CNContactViewController.descriptorForRequiredKeys()] as [Any] 
     let contact = try store.unifiedContact(withIdentifier: contactIdentifier, keysToFetch:keysToFetch as! [CNKeyDescriptor]) 

     let contactToUpdate = contact.mutableCopy() as! CNMutableContact 
     contactToUpdate.phoneNumbers = [CNLabeledValue(label: CNLabelWork, value: CNPhoneNumber(stringValue: "+440987654321"))] 

     let saveRequest = CNSaveRequest() 
     saveRequest.update(contactToUpdate) 
     try store.execute(saveRequest) 
    } catch let error{ 
     print(error) 
    } 
} 

} 

//MARK: - UITableViewDataSource 

extension MainViewController: CNContactPickerDelegate { 

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { 
    let selectedContactID = contact.identifier 
    updateContact(selectedContactID) 
} 

} 

//MARK: - UITableViewDataSource 

    extension MainViewController: UITableViewDataSource { 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return contacts.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let CellIdentifier = "MyCell" 
    let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) 
    cell!.textLabel!.text = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName 

    if let birthday = contacts[indexPath.row].birthday { 
     let formatter = DateFormatter() 
     formatter.dateStyle = DateFormatter.Style.long 
     formatter.timeStyle = .none 

     cell!.detailTextLabel?.text = formatter.string(from: ((birthday as NSDateComponents).date)!) 
    } 
    return cell! 
} 

} 

//MARK: - UITableViewDelegate 

extension MainViewController: UITableViewDelegate { 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let controller = CNContactViewController(for: contacts[indexPath.row]) 
    controller.contactStore = self.store 
    controller.allowsEditing = false 
    self.navigationController?.pushViewController(controller, animated: true) 
} 

} 

은 내가 이런 식으로 뭔가를 통합 할 필요가 알고 있지만 변수 나 올바른 유형으로 JSON 데이터를 설정 한 후 이러한 유형의

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
if segue.identifier == "showDetail" { 
    if let indexPath = self.tableView.indexPathForSelectedRow { 
     let controller = segue.destination as! ViewControllerB 
     controller.selectedName = objects[indexPath.row] 
    } 
} 
} 

의 코드를 통합 할 경우 또는 방법을 잘 모르겠습니다 끔찍한 설명에 대해 유감스럽게 생각합니다. 가능한 모든 도움을 주시면 감사하겠습니다. 저는 오랫동안 고심하고 있습니다.

+0

모델 클래스 만들기, 모델 클래스로 셀 채우기, MVC는 모델과 뷰 분리를 의미합니다. 그리고 [선택한 모델 클래스 인스턴스를 다음 ViewController에 전달하십시오] (http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – NSNoob

+1

[View Controller간에 데이터 전달] (http : //stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – NSNoob

+0

json을 사용하여 모델을 만들고 하나의 VC에서 다른 VC로 해당 모델 전달 –

답변

0

우선, 데이터를 전달하려는 다른보기 컨트롤러가 있어야합니다. 인터페이스 작성기에 있거나 프로그래밍 방식으로 수행 할 수 있습니다 (지금은 IB에 있다고 가정합니다). 그런 다음 메인 VC와 세부 VC 사이에 segue을 설정하고 식별자 등을 제공해야합니다. showDetail.

다음 세부 정보 VC가 제대로 작동하려면 필요한 데이터를 결정하는 것입니다. 각 데이터 항목 (예 : 이름, 나이, 전화, 이메일 등)에 대해 개별 변수를 가질 수 있지만 대개 많은 정보가있는 경우 데이터 모델을 사용하는 것이 가장 좋습니다. 귀하의 경우 연락처 정보를 표시하려고하기 때문에 단순히 CNContact을 다시 사용할 수 있습니다.

따라서 prepareForSegue 기능의 메인 VC에서 전환하기 전에 세부 VC에 CNContact이 필요합니다. 그리고 단서를 시작하려면 performSegue 함수를 호출하면됩니다.

적어도 방향을 제시하십시오.