Nơi niềm đam mê bắt đầu=> Swift ...

abtranbn
19/2/2015 7:13Phản hồi: 94
94 bình luận
Chia sẻ

Xu hướng

abtranbn
TÍCH CỰC
9 năm
khởi tạo cell nib:
Code:
var cellNib: UINib = UINib(nibName: "PhotoCell", bundle: nil)
abtranbn
TÍCH CỰC
9 năm
Restore in app purchase: OBJ
tạo file in app purchase: (Lưu key của ng dùng đã mua vô nsuserdefaults)vd
SLSInAppPurchase.m vs .h:
Code:
#import <Foundation/Foundation.h>

@interface SLSInAppPurchase : NSObject
+(void)setInAppPurchase;
+(BOOL)getInAppPurchase;

@end
vs
Code:
#import "SLSInAppPurchase.h"

@implementation SLSInAppPurchase
+(void)setInAppPurchase{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:[NSNumber numberWithBool:YES] forKey:@"key"];
    [defaults synchronize];
}

+(BOOL)getInAppPurchase{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults integerForKey:@"key"];
}

@end
Sau đó vô View mà để button Restore:
thêm vô sự kiện bấm:
Code:
- (IBAction)reStoreA😔id)sender {
   
    [[SKPaymentQueue defaultQueue]restoreCompletedTransactions];
}
thêm vô func:
Code:
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
    NSLog(@"%@",queue );
    NSLog(@"Restored Transactions are once again in Queue for purchasing %@",[queue transactions]);
   
    NSMutableArray *purchasedItemIDs = [[NSMutableArray alloc] init];
    NSLog(@"received restored transactions: %lu", (unsigned long)queue.transactions.count);
   
    for (SKPaymentTransaction *transaction in queue.transactions) {
        NSString *productID = transaction.payment.productIdentifier;
        [purchasedItemIDs addObject:productID];
        NSLog (@"product id is %@" , productID);
       
        [SLSInAppPurchase setInAppPurchase];
       
    }
}
abtranbn
TÍCH CỰC
9 năm
Đa nhiệm trên IOS - Lập trình multithread.
1,
BlockingMainThread vs NonBlockingMainThread:
- BlockingMainThread:
Code:
NSThread.sleepforTimeInterval(3)
. Dùng khi muốn tác vụ nào chạy xong hẳn rồi mới chạy tác vụ khác.(thằng nào được ưu tiên trước.). Trong trường hợp này là sau 3 giây mới thao tác được tiếp.
- NonBlockingMainThread: Ngược lại, Dùng khi chạy các tác vụ cùng lúc thì tác vụ trên mainthread vẫn chạy ngon lành.
- Để dùng NonBlockingMainThread ta dùng dispatch_async.

Code:
dispatch_async(dispatch_get_main_queue()){
                self.labelStatus.text = "Done"
            }



Grand Central Dispatch: (Dùng làm việc chủ yếu với server.): Là hoạt động trung tâm call center GCD.
Hoặc : NSOperation:
-Threat là gì: Là tiểu trình thực thi ứng dụng.(Xử lý giao diện, đọc, tính toán dữ liệu). Các code viết mặc định được thực thi trong tiểu trình chính- Main Threat(Threat 1.).

- Block: Trong block có tính năng của closures. Trong closures muốn goị hàm thì cần self.tên hàm.
- Main queue: dùng main thread để chạy.
- Serial queue: bắt các lệnh trong hàm này chạy một cách tuần tự.(chạy trên 1 tuyến đường)
- Concerrunt queue: là một biến instance của viewcotroller.
- dùng dispatch_async: Để không blocking cái trong hàm này.
- dùng dispatch_sync: Phải hoàn thành hoàn toàn các lệnh trong scop của nó, các câu lệnh dưới nó phải chờ nó xong.
- queue: hàng đợi có đặc điểm xếp hàng, vào trước xong trước.
- tên của queue:mainqueue, concurrent, serial
- kiểu queue: serial queue vs concurent queue
- lệnh tạo queue: let queue:
Code:
dispatch_queue_t = dispatch_queue_create("tên kiểu",kiểu queue)
2, Sync vs async:
- dùng dispatch_async: Để không blocking cái trong hàm này, hàm sau nó vs trong nó cùng chạy cùng nhau.
- dùng dispatch_sync: Blocking threat trong nó. Phải hoàn thành hoàn toàn các lệnh trong scop của nó, các câu lệnh dưới nó phải chờ nó xong.

3.


=> Mục đích: Điều khiển tác vụ chạy theo ý mình.(thằng này chạy trước xong rồi mới đến thằng khác, hay chạy song song với nhau, ưu tiên thằng nào chạy trước thằng kia chạy sau...)😃
abtranbn
TÍCH CỰC
9 năm
Xác định thiết bị (Iphone, Ipad) với Iphone SDK.
Code:
if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) {
    //Device is ipad
}else{
    //Device is iphone
}
abtranbn
TÍCH CỰC
9 năm
Feedback on Swift:

add:
Code:
import MessageUI
add to class
Code:
MFMailComposeViewControllerDelegate {
exam:
Code:
var email:UITextField?
    var sdt:UITextField?
    var chuyenmuc: UITextField?
    var body:UITextView?
    override func viewDidLoad() {
        super.viewDidLoad()
       
        self.view.backgroundColor = UIColor.whiteColor()
        var centerPoint = CGPoint(x: self.view.bounds.size.width / 2, y: self.view.bounds.size.height / 2)
        self.email?.delegate = self
        // add  email and sdt chuyen muc may tinh mac os cua tinh te
        email = UITextField(frame: CGRect(x: 20, y: 50, width: 300, height: 100))
        email?.text = "tranmanhhoang@gmail.com"
       
        email?.textColor = UIColor.blueColor()
        email?.font = UIFont(name: "Verdana Bold.ttf", size: 18)
        email?.textAlignment = NSTextAlignment.Left
        self.view.addSubview(email!)
       
        sdt = UITextField(frame: CGRect(x: 20, y: 70, width: 300, height: 100))
        sdt?.text = "0984230489"
        sdt?.font = UIFont(name: "Verdana Bold", size: 18)
        sdt?.textAlignment = NSTextAlignment.Left
        self.sdt?.delegate = self
        self.view.addSubview(sdt!)
        chuyenmuc = UITextField(frame: CGRect(x: 20, y: 90, width: 400, height: 100))
        chuyenmuc?.text = "www.tinhte.vn/forums/mac-hoi-dap-cskn.27/"
        chuyenmuc?.textAlignment = NSTextAlignment.Left
        self.view.addSubview(chuyenmuc!)
        self.chuyenmuc?.delegate = self
        email?.userInteractionEnabled = true
        var guimail: UITapGestureRecognizer?
        guimail = UITapGestureRecognizer(target: self, action: "guiMail:")
        self.view.addGestureRecognizer(guimail!)
        // Do any additional setup after loading the view.
    }
   
    func guiMail(guimail: UITapGestureRecognizer) {
        var SubjectText = " Giúp MacOS! "
        //        SubjectText +=
        var mesaageBody = body
        var nguoinhan = ["tranmanhhoang@gmail.com"]
        var mc : MFMailComposeViewController = MFMailComposeViewController()
        mc.mailComposeDelegate = self
        mc.setSubject(SubjectText)
        mc.setMessageBody(mesaageBody?.text, isHTML: false)
        mc.setToRecipients(nguoinhan)
//        self.presentedViewController(mc , animated: true , completion: nil)
        self.presentViewController(mc, animated: true, completion: nil)
    }
   
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
        switch result.value{
        case  MFMailComposeResultCancelled.value:
            NSLog("Mail cancel")

        case MFMailComposeResultFailed.value:
            NSLog("Mail fail : %@",[error.localizedDescription])
        case MFMailComposeResultSaved.value:
            NSLog("Maiil Save")
        case MFMailComposeResultSent.value:
            NSLog("Mail sent")
        default:
            break
        }
       
        self.dismissViewControllerAnimated(true, completion: nil)
    }
   
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        return false
    }
abtranbn
TÍCH CỰC
9 năm
thực hiện cuộc gọi khi ta tap vô số điện thoại:
cấu trúc :
tel:1-408-555-5555

Code:
sdt?.userInteractionEnabled = true
        let callHoang = UITapGestureRecognizer(target: self, action: "calHoang:")
        sdt?.addGestureRecognizer(callHoang)

func calHoang(tap: UITapGestureRecognizer) {
        var url = NSURL(string: "tel:0984230489")
        UIApplication.sharedApplication().openURL(url!)
    }
abtranbn
TÍCH CỰC
9 năm
thực hiện vô trang web khi ta tap vô đường link tương tự trên:
cấu trúc:
http:\\www.tinhte.vn/forums/mac-hoi-dap-cskn.27/


Code:
chuyenmuc?.userInteractionEnabled = true
        let voTinhte = UITapGestureRecognizer(target: self, action: "voTinhte:")
        chuyenmuc?.addGestureRecognizer(voTinhte)

func voTinhte(votinhte: UITapGestureRecognizer){
        var url = NSURL(string: "http://www.tinhte.vn/forums/mac-hoi-dap-cskn.27/")
        UIApplication.sharedApplication().openURL(url!)
       
    }
abtranbn
TÍCH CỰC
9 năm
thiết lập font cho uitabbar:
Code:
vc1.tabBarItem = UITabBarItem(title: "Menu", image: imagev1, tag: 1)
if let font = UIFont(name: "Chalkboard", size: 12) {
            vc1.tabBarItem.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
}
abtranbn
TÍCH CỰC
9 năm
thiết lập font cho navigation bar tilte:
Code:
self.title = "Giúp MacOS"
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Chalkboard", size: 22)!, NSForegroundColorAttributeName: UIColor.blackColor()]
abtranbn
TÍCH CỰC
9 năm
tương tự: thiết lập font barbutton: ;)
Code:
var back : UIBarButtonItem = UIBarButtonItem(title: "Quay lại", style: UIBarButtonItemStyle.Plain, target: self, action: "backview")
        if let font = UIFont(name: "Chalkboard", size: 16) {
            back.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
        }
self.navigationItem.leftBarButtonItem = back
func backview() {

        if let navController = self.navigationController {

            navController.popViewControllerAnimated(true)

        }

    }
hlp
ĐẠI BÀNG
9 năm
Bác này cũng có kiểu viết 1 cẩm nang lưu lại những công thức khi cần trong swift như mềnh 😃
Screen Shot 2015-03-30 at 2.23.58 PM.png
abtranbn
TÍCH CỰC
9 năm
@hlp 🆒🆒🆒 chia sẻ cho anh em lên đây luôn đi bạn.
abtranbn
TÍCH CỰC
9 năm
ẩn bàn phím khi drag tableview hoặc scrollview:
set the Keyboard field to Dismiss on Drag.
abtranbn
TÍCH CỰC
9 năm
nếu khai báo kiểu này khi search sẽ crash (url sẽ nil) 😔:
Code:
url = NSURL(string: "http://mmovie.hdviet.com/tim-kiem-theo-loai.html?key=\(searchBar.text)&&page=\(currentPage)")
tìm kiếm với nsurl là tiếng việt (tổng quát : Non English) cần khai báo và làm như sau;):

Code:
var timkiem = "http://mmovie.hdviet.com/tim-kiem-theo-loai.html?key="

timkiem += searchBar.text
            url = NSURL(string: timkiem.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
abtranbn
TÍCH CỰC
9 năm
Chú ý: khi ta nhấn longpress công việc trong hàm sẽ được gọi 2 lần (bắt đầu và kết thúc gọi phát) cho nên nếu chỉ muốn gọi 1 phát thì cần bỏ trống 1 chỗ:

Code:
func giam1may(sender: UILongPressGestureRecognizer) {
        if (sender.state == UIGestureRecognizerState.Ended){
           
        }
        if (sender.state == UIGestureRecognizerState.Began) {
                t -= 1
            NSUserDefaults.standardUserDefaults().setInteger(t, forKey: "somaymac")
            NSUserDefaults.standardUserDefaults().synchronize()
                NSLog("giam 1 may")
                hienthisomaycon()
                
        }
abtranbn
TÍCH CỰC
9 năm
màu ngẫu nhiên :
Code:
func randomcolor()-> UIColor {
        var randomRed:CGFloat = CGFloat(drand48())
        var randomGreen:CGFloat = CGFloat(drand48())
        var randimBlue:CGFloat = CGFloat(drand48())
        return UIColor(red: randomRed, green: randomGreen, blue: randimBlue, alpha: 1.0)
    }
abtranbn
TÍCH CỰC
9 năm
bật đèn flash iphone :
Code:
    func toggleTorch() {
        let avDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        // check if the device has torch
        if  avDevice.hasTorch {
            // lock your device for configuration
            avDevice.lockForConfiguration(nil)
            // check if your torchMode is on or off. If on turns it off otherwise turns it on
            avDevice.torchMode = avDevice.torchActive ? AVCaptureTorchMode.Off : AVCaptureTorchMode.On
           
            // sets the torch intensity to 100%
            avDevice.setTorchModeOnWithLevel(1.0, error: nil)
            // unlock your device
            avDevice.unlockForConfiguration()
           
        }
    }
abtranbn
TÍCH CỰC
9 năm
có bật rồi phải có tắt flash.
Code:
func toggleTorchOff() {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        if (device.hasTorch) {
            device.lockForConfiguration(nil)
            let torchOn = !device.torchActive
            device.setTorchModeOnWithLevel(1.0, error: nil)
            device.torchMode = torchOn ? AVCaptureTorchMode.On : AVCaptureTorchMode.Off
            device.unlockForConfiguration()
        }
    }
abtranbn
TÍCH CỰC
9 năm
kiểm tra kết nối internet vs AFNetworking:
Code:
func checkNet() {
        AFNetworkReachabilityManager.sharedManager().startMonitoring()
        AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status:AFNetworkReachabilityStatus) -> Void in
            switch status.hashValue{
            case AFNetworkReachabilityStatus.NotReachable.hashValue:
                NSLog("Not reachable")
            case AFNetworkReachabilityStatus.ReachableViaWiFi.hashValue , AFNetworkReachabilityStatus.ReachableViaWWAN.hashValue :
                NSLog("Reachable")
            default:
                NSLog("Unknown status")
            }}
    }
abtranbn
TÍCH CỰC
9 năm
ẩn bàn phím khi tích vô view chính vs uinavigationBar:
Code:
func setupGestureRecognizer() {
        let dismissKeyboardTap = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        dismissKeyboardTap.cancelsTouchesInView = false
     
        self.navigationController?.navigationBar.addGestureRecognizer(dismissKeyboardTap)
    }
    func setupGestureRecognizer2() {
        let dismissKeyboardTap = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        dismissKeyboardTap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(dismissKeyboardTap)
    }
 
    func dismissKeyboard() {
        self.view.endEditing(true)
    }
ObjectiveC:
Code:
 UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
                                           initWithTarget:self
                                           action:@selector(hideKeyBoard)];
   
    [self.view addGestureRecognizer:tapGesture];

-(void)hideKeyBoard {
    [_titleTextField resignFirstResponder];
    [_contentTextView resignFirstResponder];
}
abtranbn
TÍCH CỰC
9 năm
Ứng dụng Giúp Mac giúp các bạn đây:
https://itunes.apple.com/vn/app/giup-mac/id985144970?mt=8

Xu hướng

Bài mới









  • Chịu trách nhiệm nội dung: Trần Mạnh Hiệp
  • © 2024 Công ty Cổ phần MXH Tinh Tế
  • Địa chỉ: Số 70 Bà Huyện Thanh Quan, P. Võ Thị Sáu, Quận 3, TPHCM
  • Số điện thoại: 02822460095
  • MST: 0313255119
  • Giấy phép thiết lập MXH số 11/GP-BTTTT, Ký ngày: 08/01/2019