小编use*_*888的帖子

如何在swift中保存和读取NSUserdefaults中的数组数组?

我需要创建一个数组来添加这种格式的对象,如Swift中的字典:["key1":"value1","key2":"value2"]

当我尝试保存它时,NSUserDefaults一切都是正确的,但是当NSUserDefaults用键读取时这会崩溃.我的var obj需要什么类型的数据?

let def = NSUserDefaults.standardUserDefaults()
var key = "keySave"
var element: AnyObject!

var array1: [AnyObject!] = []
array1.append(["key1": "val1", "key2": "val2"])
array1.append(["key1": "val1", "key2": "val2"])

//save
var savestring : [AnyObject!]
savestring = array1
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(savestring, forKey: key)
defaults.synchronize()

//read
var obj: [AnyObject!] = []
if(obj != nil){
    print("size: ")
    print(obj.count) //vary long value confused..
    element = obj[0]  //crash
    print(element.objectForKey("key1"))
}
Run Code Online (Sandbox Code Playgroud)

nsuserdefaults swift xcode6

71
推荐指数
5
解决办法
8万
查看次数

如何在swift中将此var字符串转换为NSURL

我需要url filepath是一个NSURL.我有这个:

let paths = NSSearchPathForDirectoriesInDomains(
        .documentDirectory, .userDomainMask, true)

// NSString *documentsDirectory = [paths objectAtIndex:0];
let documentsDirectory = paths[0] as String

var filePath:String? = nil
var fileNamePostfix = 0
repeat {
    filePath =
    "\(documentsDirectory)/\(dateTimePrefix)-\(fileNamePostfix).mp4"
    fileNamePostfix += 1
} while (FileManager.default.fileExists(atPath: filePath))
Run Code Online (Sandbox Code Playgroud)

我需要将它转换为NSURL以便在self.fileOutput.startRecordingToOutputFileURL(<#outputFileURL:NSURL?#>,recordingDelegate:<#AVCaptureFileOutputRecordingDelegate?#>)方法中使用.

我试过self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>)但不正确

谢谢!

nsurl ios swift

67
推荐指数
4
解决办法
10万
查看次数

如何在Swift中正确设置imageView在sqContacts中?

我希望将图片显示为imageView,如图像联系人(在一个圆圈中)但是当我尝试显示这个时,imageView会重新调整他的大小,这在圆圈中无法正确显示.

 image.layer.borderWidth=1.0
 image.layer.masksToBounds = false
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)

我想要这样的节目: 在此输入图像描述

但我明白了: 在此输入图像描述

如何将该图像调整为UIImageView大小以显示为圆圈?

谢谢!

uiimageview ios swift xcode6

47
推荐指数
9
解决办法
7万
查看次数

如何在swift中使用UIImagePickerController捕获相机?

我正在尝试UIImagePickerController快速使用但不工作......

我的ViewController:

class ViewController: UIViewController {

@IBOutlet var imag : UIView = nil
@IBAction func capture(sender : UIButton) {
    println("Button capture")
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
    {
        var imag = UIImagePickerController()
        imag.delegate = self
        imag.sourceType = UIImagePickerControllerSourceType.Camera;
       imag.mediaTypes = kUTTypeImage
        imag.allowsEditing = false

        self.presentViewController(imag, animated: true, completion: nil)

    }
   }   
}
Run Code Online (Sandbox Code Playgroud)

我在下面的代码行中有错误

imag.delegate = self 
(Type'ViewControlles does confoorm to protocol 'UIImagePickerControllerDelegate')
imagePicker.mediaTypes = kUTTypeImage   
(use of unresolved identifier kUTTypeImage)
Run Code Online (Sandbox Code Playgroud)

我已经阅读过kUTTypeImage在swift 中无法使用的内容.但是我不知道,我正在使用这个函数.有帮助吗?

谢谢!!

uiimagepickercontroller swift xcode6 ios8

36
推荐指数
5
解决办法
4万
查看次数

使用Swift中的NSDateComponents计算出生日期的年龄

我正在尝试使用此函数计算Swift中birthdayDate的年龄:

var calendar : NSCalendar = NSCalendar.currentCalendar()

var dateComponentNow : NSDateComponents = calendar.components(
             NSCalendarUnit.CalendarUnitYear, 
             fromDate: birthday, 
             toDate: age, 
             options: 0)
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误 Extra argument toDate in call

在目标c中这是代码,但我不知道为什么会出现此错误:

NSDate* birthday = ...;

NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar] 
                               components:NSYearCalendarUnit 
                               fromDate:birthday
                               toDate:now
                               options:0];
NSInteger age = [ageComponents year]; 
Run Code Online (Sandbox Code Playgroud)

有没有比这更好的形式?

nsdatecomponents swift

33
推荐指数
3
解决办法
3万
查看次数

添加adMob时未定义的体系结构符号

我正在为我的项目添加admob,但是我收到了这个错误:

架构i386的未定义符号:

 "_OBJC_CLASS_$_EKEvent", referenced from:
      objc-class-ref in libGoogleAdMobAds.a(GADOpener.o)
  "_OBJC_CLASS_$_EKEventEditViewController", referenced from:
      objc-class-ref in libGoogleAdMobAds.a(GADOpener.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)

我已经添加了:

StoreKit
AudioToolbox
MessageUI
SystemConfiguration
CoreGraphics
AdSupport
Run Code Online (Sandbox Code Playgroud)

并且还使用-ObjC链接标志..

问题是什么?

谢谢!

xcode objective-c admob

22
推荐指数
2
解决办法
1万
查看次数

如何在Swift中选择与ABPeoplePickerNavigationController的联系?

我已将其添加ABPeoplePickerNavigationController到我的第一个视图控制器中.我希望当我选择一个联系人时显示要在其他视图控制器中显示的信息,但我正在尝试使用我的代码,这在我点击联系人时不会显示.这只会打开联系人到本机应用程序ABPeoplePickerNavigationController.

var people = ABPeoplePickerNavigationController()
var addressBook: ABAddressBookRef?

func extractABAddressBookRef(abRef: Unmanaged<ABAddressBookRef>!) -> ABAddressBookRef? {
    if let ab = abRef {
        self.view.addSubview(people.view)
        return Unmanaged<NSObject>.fromOpaque(ab.toOpaque()).takeUnretainedValue()
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

我试过这个功能

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!,didSelectPerson person: ABRecordRef!) {

    var unmanagedEmails = ABRecordCopyValue(people, kABPersonEmailProperty)
    let emailObj: ABMultiValueRef = Unmanaged.fromOpaque(unmanagedEmails.toOpaque()).takeUnretainedValue() as NSObject as ABMultiValueRef

    var index = 0 as CFIndex

    var unmanagedEmail = ABMultiValueCopyValueAtIndex(emailObj, index)
    var emailAddress:String = Unmanaged.fromOpaque(unmanagedEmail.toOpaque()).takeUnretainedValue() as NSObject as String

    println(emailAddress)      
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

addressbook peoplepicker abaddressbook addressbookui swift

17
推荐指数
3
解决办法
2万
查看次数

如何在swift中获取CLLocationManager的位置用户?

我在我的视图控制器上有这个代码,但这不起作用:

  import UIKit
  import CoreLocation

  class ViewController: UIViewController, CLLocationManagerDelegate {

   var location: CLLocationManager!

  override func viewDidLoad() {
     super.viewDidLoad()

     location=CLLocationManager()
     location.delegate = self
     location.desiredAccuracy=kCLLocationAccuracyBest
     location.startUpdatingLocation()
 }

  func locationManager(location:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
     println("locations = \(locations)")
     label1.text = "success"
 }
Run Code Online (Sandbox Code Playgroud)

我对其他帖子中的阅读方式有所了解.但我没有得到永远,没有印刷品..

谢谢!!

core-location cllocationmanager ios swift

14
推荐指数
3
解决办法
4万
查看次数

如何将代码目标c转换为Swift以保存图像?

我在其他帖子中看到过这段代码,用于保存图片:

  // Create path.
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,      NSUserDomainMask, YES);
 NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
Run Code Online (Sandbox Code Playgroud)

我正在尝试转换为swift以保存带有avfoundatioin的图片但我不知道类型NSDocumentDirectory和NSUserDomainMask这里如何转换这个?

谢谢!!

path avfoundation nsdocumentdirectory swift

10
推荐指数
1
解决办法
8936
查看次数

如何初始化UIBezierPath以在swift中绘制圆圈?

我试图在Swift中绘制一个圆圈,但是当我编写代码时,我得到一个错误"无法找到接受提供的参数的'init'的重载.

在类UIBezierPath中有一个init函数:

 init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> UIBezierPath
Run Code Online (Sandbox Code Playgroud)

但是当我用这个代码声明这个时我得到错误..需要我将任何变量转换为其他类型吗?但如果我在iphone 4中编译了这个,我没有得到错误,只在iphone 5/5s.怎么能正确地声明这个?

  let arcCenter   = CGPoint(x: CGRectGetMidX(self.bounds), y: CGRectGetMidY(self.bounds))
    let radius      = Float(min(CGRectGetMidX(self.bounds) - 1, CGRectGetMidY(self.bounds)-1))

    let circlePath : UIBezierPath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: -rad(90), endAngle: rad(360-90), clockwise: true)
Run Code Online (Sandbox Code Playgroud)

谢谢!

uibezierpath swift xcode6

7
推荐指数
1
解决办法
1万
查看次数